UNPKG

@nx/devkit

Version:

The Nx Devkit is used to customize Nx for different technologies and use cases. It contains many utility functions for reading and writing files, updating configuration, working with Abstract Syntax Trees(ASTs), and more. Learn more about [extending Nx by

103 lines (102 loc) 3.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatFiles = formatFiles; const path = require("path"); const devkit_exports_1 = require("nx/src/devkit-exports"); const devkit_internals_1 = require("nx/src/devkit-internals"); /** * Formats all the created or updated files using Prettier * @param tree - the file system tree */ async function formatFiles(tree, options = { /** * TODO(v21): Stop sorting tsconfig paths by default, paths are now less common/important * in Nx workspace setups, and the sorting causes comments to be lost. */ sortRootTsconfigPaths: true, }) { let prettier; try { prettier = await Promise.resolve().then(() => require('prettier')); /** * Even after we discovered prettier in node_modules, we need to be sure that the user is intentionally using prettier * before proceeding to format with it. */ if (!(0, devkit_internals_1.isUsingPrettierInTree)(tree)) { return; } } catch { } if (options.sortRootTsconfigPaths) { sortTsConfig(tree); } if (!prettier) return; const files = new Set(tree.listChanges().filter((file) => file.type !== 'DELETE')); const changedPrettierInTree = getChangedPrettierConfigInTree(tree); await Promise.all(Array.from(files).map(async (file) => { try { const systemPath = path.join(tree.root, file.path); const resolvedOptions = await prettier.resolveConfig(systemPath, { editorconfig: true, }); const options = { ...resolvedOptions, ...changedPrettierInTree, filepath: systemPath, }; if (file.path.endsWith('.swcrc')) { options.parser = 'json'; } const support = await prettier.getFileInfo(systemPath, options); if (support.ignored || !support.inferredParser) { return; } tree.write(file.path, // In prettier v3 the format result is a promise await prettier.format(file.content.toString('utf-8'), options)); } catch (e) { console.warn(`Could not format ${file.path}. Error: "${e.message}"`); } })); } function sortTsConfig(tree) { try { const tsConfigPath = getRootTsConfigPath(tree); if (!tsConfigPath) { return; } (0, devkit_exports_1.updateJson)(tree, tsConfigPath, (tsconfig) => ({ ...tsconfig, compilerOptions: { ...tsconfig.compilerOptions, paths: (0, devkit_internals_1.sortObjectByKeys)(tsconfig.compilerOptions.paths), }, })); } catch (e) { // catch noop } } function getRootTsConfigPath(tree) { for (const path of ['tsconfig.base.json', 'tsconfig.json']) { if (tree.exists(path)) { return path; } } return null; } function getChangedPrettierConfigInTree(tree) { if (tree.listChanges().find((file) => file.path === '.prettierrc')) { try { return (0, devkit_exports_1.readJson)(tree, '.prettierrc'); } catch { return null; } } else { return null; } }