diff --git a/packages/devkit/src/generators/format-files.ts b/packages/devkit/src/generators/format-files.ts index b4dda3e5a5..bcc2a3d89c 100644 --- a/packages/devkit/src/generators/format-files.ts +++ b/packages/devkit/src/generators/format-files.ts @@ -47,6 +47,10 @@ export async function formatFiles(tree: Tree): Promise { ...resolvedOptions, }; + if (file.path.endsWith('.swcrc')) { + options.parser = 'json'; + } + const support = await prettier.getFileInfo(systemPath, options); if (support.ignored || !support.inferredParser) { return; diff --git a/packages/js/src/utils/swc/add-swc-config.ts b/packages/js/src/utils/swc/add-swc-config.ts index 6ac7c2bd04..eca563191e 100644 --- a/packages/js/src/utils/swc/add-swc-config.ts +++ b/packages/js/src/utils/swc/add-swc-config.ts @@ -1,6 +1,6 @@ // TODO(chau): change back to 2015 when https://github.com/swc-project/swc/issues/1108 is solved // target: 'es2015' -import { Tree } from '@nrwl/devkit'; +import { logger, readJson, Tree, updateJson } from '@nrwl/devkit'; import { join } from 'path'; export const defaultExclude = [ @@ -40,6 +40,5 @@ const swcOptionsString = () => `{ export function addSwcConfig(tree: Tree, projectDir: string) { const swcrcPath = join(projectDir, '.lib.swcrc'); if (tree.exists(swcrcPath)) return; - tree.write(swcrcPath, swcOptionsString()); } diff --git a/packages/nx/src/command-line/format.ts b/packages/nx/src/command-line/format.ts index 3f9177edb1..0ac3d33364 100644 --- a/packages/nx/src/command-line/format.ts +++ b/packages/nx/src/command-line/format.ts @@ -83,10 +83,16 @@ async function getPatterns( } const p = parseFiles(args); + const supportedExtensions = prettier .getSupportInfo() .languages.flatMap((language) => language.extensions) - .filter((extension) => !!extension); + .filter((extension) => !!extension) + // Prettier supports ".swcrc" as a file instead of an extension + // So we add ".swcrc" as a supported extension manually + // which allows it to be considered for calculating "patterns" + .concat('.swcrc'); + const patterns = p.files.filter( (f) => fileExists(f) && supportedExtensions.includes(path.extname(f)) ); @@ -151,12 +157,33 @@ function chunkify(target: string[], size: number): string[][] { function write(patterns: string[]) { if (patterns.length > 0) { + const [swcrcPatterns, regularPatterns] = patterns.reduce( + (result, pattern) => { + result[pattern.includes('.swcrc') ? 0 : 1].push(pattern); + return result; + }, + [[], []] as [swcrcPatterns: string[], regularPatterns: string[]] + ); + execSync( - `node "${PRETTIER_PATH}" --write --list-different ${patterns.join(' ')}`, + `node "${PRETTIER_PATH}" --write --list-different ${regularPatterns.join( + ' ' + )}`, { stdio: [0, 1, 2], } ); + + if (swcrcPatterns.length > 0) { + execSync( + `node "${PRETTIER_PATH}" --write --list-different ${swcrcPatterns.join( + ' ' + )} --parser json`, + { + stdio: [0, 1, 2], + } + ); + } } }