@nx/js 20.3.1 → 20.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  (The MIT License)
2
2
 
3
- Copyright (c) 2017-2024 Narwhal Technologies Inc.
3
+ Copyright (c) 2017-2025 Narwhal Technologies Inc.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining
6
6
  a copy of this software and associated documentation files (the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/js",
3
- "version": "20.3.1",
3
+ "version": "20.3.3",
4
4
  "private": false,
5
5
  "description": "The JS plugin for Nx contains executors and generators that provide the best experience for developing JavaScript and TypeScript projects. ",
6
6
  "repository": {
@@ -39,8 +39,8 @@
39
39
  "@babel/preset-env": "^7.23.2",
40
40
  "@babel/preset-typescript": "^7.22.5",
41
41
  "@babel/runtime": "^7.22.6",
42
- "@nx/devkit": "20.3.1",
43
- "@nx/workspace": "20.3.1",
42
+ "@nx/devkit": "20.3.3",
43
+ "@nx/workspace": "20.3.3",
44
44
  "@zkochan/js-yaml": "0.0.7",
45
45
  "babel-plugin-const-enum": "^1.0.1",
46
46
  "babel-plugin-macros": "^2.8.0",
@@ -29,9 +29,7 @@ function normalizeOptions(options, root, sourceRoot, projectRoot) {
29
29
  }
30
30
  }
31
31
  const outputPath = (0, path_1.join)(root, options.outputPath);
32
- if (options.skipTypeCheck == null && !isTsSolutionSetup) {
33
- options.skipTypeCheck = false;
34
- }
32
+ options.skipTypeCheck ??= !isTsSolutionSetup;
35
33
  if (options.watch == null) {
36
34
  options.watch = false;
37
35
  }
@@ -1,4 +1,4 @@
1
- import { <%= propertyName %> } from './<%= fileName %>';
1
+ import { <%= propertyName %> } from './<%= fileNameImport %>';
2
2
 
3
3
  describe('<%= propertyName %>', () => {
4
4
  it('should work', () => {
@@ -11,18 +11,19 @@ const log_show_project_command_1 = require("@nx/devkit/src/utils/log-show-projec
11
11
  const find_matching_projects_1 = require("nx/src/utils/find-matching-projects");
12
12
  const path_1 = require("path");
13
13
  const generator_prompts_1 = require("../../utils/generator-prompts");
14
- const package_manager_workspaces_1 = require("../../utils/package-manager-workspaces");
14
+ const update_package_json_1 = require("../../utils/package-json/update-package-json");
15
15
  const add_swc_config_1 = require("../../utils/swc/add-swc-config");
16
16
  const add_swc_dependencies_1 = require("../../utils/swc/add-swc-dependencies");
17
17
  const configuration_1 = require("../../utils/typescript/configuration");
18
18
  const create_ts_config_1 = require("../../utils/typescript/create-ts-config");
19
+ const ensure_typescript_1 = require("../../utils/typescript/ensure-typescript");
19
20
  const plugin_1 = require("../../utils/typescript/plugin");
20
21
  const ts_config_1 = require("../../utils/typescript/ts-config");
21
22
  const ts_solution_setup_1 = require("../../utils/typescript/ts-solution-setup");
22
23
  const versions_1 = require("../../utils/versions");
23
24
  const init_1 = require("../init/init");
24
25
  const generator_1 = require("../setup-verdaccio/generator");
25
- const ensure_typescript_1 = require("../../utils/typescript/ensure-typescript");
26
+ const sort_fields_1 = require("../../utils/package-json/sort-fields");
26
27
  const defaultOutputDirectory = 'dist';
27
28
  async function libraryGenerator(tree, schema) {
28
29
  return await libraryGeneratorInternal(tree, {
@@ -55,7 +56,7 @@ async function libraryGeneratorInternal(tree, schema) {
55
56
  await configurationGenerator(tree, {
56
57
  project: options.name,
57
58
  compiler: 'swc',
58
- format: ['cjs', 'esm'],
59
+ format: options.isUsingTsSolutionConfig ? ['esm'] : ['cjs', 'esm'],
59
60
  });
60
61
  }
61
62
  if (options.bundler === 'vite') {
@@ -101,6 +102,7 @@ async function libraryGeneratorInternal(tree, schema) {
101
102
  testEnvironment: options.testEnvironment,
102
103
  runtimeTsconfigFileName: 'tsconfig.lib.json',
103
104
  compiler: options.compiler === 'swc' ? 'swc' : 'babel',
105
+ addPlugin: options.addPlugin,
104
106
  });
105
107
  tasks.push(vitestTask);
106
108
  createOrEditViteConfig(tree, {
@@ -120,17 +122,22 @@ async function libraryGeneratorInternal(tree, schema) {
120
122
  // add project reference to the runtime tsconfig.lib.json file
121
123
  json.references ??= [];
122
124
  json.references.push({ path: './tsconfig.lib.json' });
125
+ if (options.isUsingTsSolutionConfig && options.bundler === 'rollup') {
126
+ json.compilerOptions.module = 'esnext';
127
+ json.compilerOptions.moduleResolution = 'bundler';
128
+ }
123
129
  return json;
124
130
  });
125
131
  }
132
+ // If we are using the new TS solution
133
+ // We need to update the workspace file (package.json or pnpm-workspaces.yaml) to include the new project
134
+ if (options.isUsingTsSolutionConfig) {
135
+ (0, ts_solution_setup_1.addProjectToTsSolutionWorkspace)(tree, options.projectRoot);
136
+ }
137
+ (0, sort_fields_1.sortPackageJsonFields)(tree, options.projectRoot);
126
138
  if (!options.skipFormat) {
127
139
  await (0, devkit_1.formatFiles)(tree);
128
140
  }
129
- if (!options.skipWorkspacesWarning &&
130
- options.isUsingTsSolutionConfig &&
131
- options.projectPackageManagerWorkspaceState !== 'included') {
132
- tasks.push((0, package_manager_workspaces_1.getProjectPackageManagerWorkspaceStateWarningTask)(options.projectPackageManagerWorkspaceState, tree.root));
133
- }
134
141
  if (options.publishable) {
135
142
  tasks.push(() => {
136
143
  logNxReleaseDocsInfo();
@@ -138,7 +145,7 @@ async function libraryGeneratorInternal(tree, schema) {
138
145
  }
139
146
  // Always run install to link packages.
140
147
  if (options.isUsingTsSolutionConfig) {
141
- tasks.push(() => (0, devkit_1.installPackagesTask)(tree));
148
+ tasks.push(() => (0, devkit_1.installPackagesTask)(tree, true));
142
149
  }
143
150
  tasks.push(() => {
144
151
  (0, log_show_project_command_1.logShowProjectCommand)(options.name);
@@ -175,15 +182,13 @@ async function configureProject(tree, options) {
175
182
  tsConfig: `${options.projectRoot}/tsconfig.lib.json`,
176
183
  },
177
184
  };
178
- if (options.bundler === 'esbuild') {
179
- projectConfiguration.targets.build.options.format = ['cjs'];
180
- }
181
185
  if (options.bundler === 'swc' &&
182
186
  (options.skipTypeCheck || options.isUsingTsSolutionConfig)) {
183
187
  projectConfiguration.targets.build.options.skipTypeCheck = true;
184
188
  }
185
189
  if (options.isUsingTsSolutionConfig) {
186
190
  if (options.bundler === 'esbuild') {
191
+ projectConfiguration.targets.build.options.format = ['esm'];
187
192
  projectConfiguration.targets.build.options.declarationRootDir = `${options.projectRoot}/src`;
188
193
  }
189
194
  else if (options.bundler === 'swc') {
@@ -193,6 +198,7 @@ async function configureProject(tree, options) {
193
198
  else {
194
199
  projectConfiguration.targets.build.options.assets = [];
195
200
  if (options.bundler === 'esbuild') {
201
+ projectConfiguration.targets.build.options.format = ['cjs'];
196
202
  projectConfiguration.targets.build.options.generatePackageJson = true;
197
203
  }
198
204
  if (!options.minimal) {
@@ -301,19 +307,21 @@ async function addLint(tree, options) {
301
307
  ruleSeverity = value;
302
308
  ruleOptions = {};
303
309
  }
304
- if (options.bundler === 'vite' || options.unitTestRunner === 'vitest') {
305
- ruleOptions.ignoredFiles ??= [];
306
- ruleOptions.ignoredFiles.push('{projectRoot}/vite.config.{js,ts,mjs,mts}');
307
- o.rules['@nx/dependency-checks'] = [ruleSeverity, ruleOptions];
310
+ const ignoredFiles = new Set(ruleOptions.ignoredFiles ?? []);
311
+ if (options.bundler === 'vite') {
312
+ ignoredFiles.add('{projectRoot}/vite.config.{js,ts,mjs,mts}');
308
313
  }
309
314
  else if (options.bundler === 'rollup') {
310
- ruleOptions.ignoredFiles ??= [];
311
- ruleOptions.ignoredFiles.push('{projectRoot}/rollup.config.{js,ts,mjs,mts}');
312
- o.rules['@nx/dependency-checks'] = [ruleSeverity, ruleOptions];
315
+ ignoredFiles.add('{projectRoot}/rollup.config.{js,ts,mjs,mts,cjs,cts}');
313
316
  }
314
317
  else if (options.bundler === 'esbuild') {
315
- ruleOptions.ignoredFiles ??= [];
316
- ruleOptions.ignoredFiles.push('{projectRoot}/esbuild.config.{js,ts,mjs,mts}');
318
+ ignoredFiles.add('{projectRoot}/esbuild.config.{js,ts,mjs,mts}');
319
+ }
320
+ if (options.unitTestRunner === 'vitest') {
321
+ ignoredFiles.add('{projectRoot}/vite.config.{js,ts,mjs,mts}');
322
+ }
323
+ if (ignoredFiles.size) {
324
+ ruleOptions.ignoredFiles = Array.from(ignoredFiles);
317
325
  o.rules['@nx/dependency-checks'] = [ruleSeverity, ruleOptions];
318
326
  }
319
327
  return o;
@@ -332,7 +340,7 @@ function createFiles(tree, options) {
332
340
  const { className, name, propertyName } = (0, devkit_1.names)(options.projectNames.projectFileName);
333
341
  createProjectTsConfigs(tree, options);
334
342
  let fileNameImport = options.fileName;
335
- if (options.bundler === 'vite') {
343
+ if (options.bundler === 'vite' || options.isUsingTsSolutionConfig) {
336
344
  const tsConfig = (0, ts_config_1.readTsConfigFromTree)(tree, (0, path_1.join)(options.projectRoot, 'tsconfig.lib.json'));
337
345
  const ts = (0, ensure_typescript_1.ensureTypescript)();
338
346
  if (tsConfig.options.moduleResolution === ts.ModuleResolutionKind.Node16 ||
@@ -376,7 +384,9 @@ function createFiles(tree, options) {
376
384
  });
377
385
  }
378
386
  if (options.bundler === 'swc' || options.bundler === 'rollup') {
379
- (0, add_swc_config_1.addSwcConfig)(tree, options.projectRoot, options.bundler === 'swc' ? 'commonjs' : 'es6');
387
+ (0, add_swc_config_1.addSwcConfig)(tree, options.projectRoot, options.bundler === 'swc' && !options.isUsingTsSolutionConfig
388
+ ? 'commonjs'
389
+ : 'es6');
380
390
  }
381
391
  else if (options.includeBabelRc) {
382
392
  addBabelRc(tree, options);
@@ -405,7 +415,7 @@ function createFiles(tree, options) {
405
415
  // https://docs.npmjs.com/cli/v10/configuring-npm/package-json#files
406
416
  json.files = ['dist', '!**/*.tsbuildinfo'];
407
417
  }
408
- return {
418
+ const updatedPackageJson = {
409
419
  ...json,
410
420
  dependencies: {
411
421
  ...json.dependencies,
@@ -413,10 +423,25 @@ function createFiles(tree, options) {
413
423
  },
414
424
  ...determineEntryFields(options),
415
425
  };
426
+ if (options.bundler === 'none') {
427
+ updatedPackageJson.type = 'module';
428
+ }
429
+ else if (options.bundler !== 'vite' && options.bundler !== 'rollup') {
430
+ return (0, update_package_json_1.getUpdatedPackageJsonContent)(updatedPackageJson, {
431
+ main: (0, path_1.join)(options.projectRoot, 'src/index.ts'),
432
+ outputPath: (0, devkit_1.joinPathFragments)(options.projectRoot, 'dist'),
433
+ projectRoot: options.projectRoot,
434
+ rootDir: (0, path_1.join)(options.projectRoot, 'src'),
435
+ generateExportsField: true,
436
+ packageJsonPath,
437
+ format: ['esm'],
438
+ });
439
+ }
440
+ return updatedPackageJson;
416
441
  });
417
442
  }
418
443
  else {
419
- const packageJson = {
444
+ let packageJson = {
420
445
  name: options.importPath,
421
446
  version: '0.0.1',
422
447
  dependencies: determineDependencies(options),
@@ -430,6 +455,22 @@ function createFiles(tree, options) {
430
455
  // https://docs.npmjs.com/cli/v10/configuring-npm/package-json#files
431
456
  packageJson.files = ['dist', '!**/*.tsbuildinfo'];
432
457
  }
458
+ if (options.isUsingTsSolutionConfig) {
459
+ if (options.bundler === 'none') {
460
+ packageJson.type = 'module';
461
+ }
462
+ else if (options.bundler !== 'vite' && options.bundler !== 'rollup') {
463
+ packageJson = (0, update_package_json_1.getUpdatedPackageJsonContent)(packageJson, {
464
+ main: (0, path_1.join)(options.projectRoot, 'src/index.ts'),
465
+ outputPath: (0, devkit_1.joinPathFragments)(options.projectRoot, 'dist'),
466
+ projectRoot: options.projectRoot,
467
+ rootDir: (0, path_1.join)(options.projectRoot, 'src'),
468
+ generateExportsField: true,
469
+ packageJsonPath,
470
+ format: ['esm'],
471
+ });
472
+ }
473
+ }
433
474
  (0, devkit_1.writeJson)(tree, packageJsonPath, packageJson);
434
475
  }
435
476
  if (options.config === 'npm-scripts') {
@@ -441,6 +482,12 @@ function createFiles(tree, options) {
441
482
  return json;
442
483
  });
443
484
  }
485
+ else if (!options.isUsingTsSolutionConfig &&
486
+ options.useProjectJson &&
487
+ (!options.bundler || options.bundler === 'none') &&
488
+ !(options.projectRoot === '.')) {
489
+ tree.delete(packageJsonPath);
490
+ }
444
491
  if (options.minimal && !(options.projectRoot === '.')) {
445
492
  tree.delete((0, path_1.join)(options.projectRoot, 'README.md'));
446
493
  }
@@ -577,7 +624,6 @@ async function normalizeOptions(tree, options) {
577
624
  ? options.tags.split(',').map((s) => s.trim())
578
625
  : [];
579
626
  options.minimal ??= false;
580
- const projectPackageManagerWorkspaceState = (0, package_manager_workspaces_1.getProjectPackageManagerWorkspaceState)(tree, projectRoot);
581
627
  // We default to generate a project.json file if the new setup is not being used
582
628
  options.useProjectJson ??= !isUsingTsSolutionConfig;
583
629
  return {
@@ -590,7 +636,6 @@ async function normalizeOptions(tree, options) {
590
636
  importPath,
591
637
  hasPlugin,
592
638
  isUsingTsSolutionConfig,
593
- projectPackageManagerWorkspaceState,
594
639
  };
595
640
  }
596
641
  function addProjectDependencies(tree, options) {
@@ -774,75 +819,87 @@ function determineDependencies(options) {
774
819
  function determineEntryFields(options) {
775
820
  switch (options.bundler) {
776
821
  case 'tsc':
777
- return {
778
- type: 'commonjs',
779
- main: options.isUsingTsSolutionConfig
780
- ? './dist/index.js'
781
- : './src/index.js',
782
- typings: options.isUsingTsSolutionConfig
783
- ? './dist/index.d.ts'
784
- : './src/index.d.ts',
785
- };
786
822
  case 'swc':
787
- return {
788
- type: 'commonjs',
789
- main: options.isUsingTsSolutionConfig
790
- ? './dist/index.js'
791
- : './src/index.js',
792
- typings: options.isUsingTsSolutionConfig
793
- ? './dist/index.d.ts'
794
- : './src/index.d.ts',
795
- };
823
+ if (options.isUsingTsSolutionConfig) {
824
+ return {
825
+ type: 'module',
826
+ main: './dist/index.js',
827
+ types: './dist/index.d.ts',
828
+ };
829
+ }
830
+ else {
831
+ return {
832
+ type: 'commonjs',
833
+ main: './src/index.js',
834
+ types: './src/index.d.ts',
835
+ };
836
+ }
796
837
  case 'rollup':
797
- return {
798
- // Since we're publishing both formats, skip the type field.
799
- // Bundlers or Node will determine the entry point to use.
800
- main: options.isUsingTsSolutionConfig
801
- ? './dist/index.cjs'
802
- : './index.cjs',
803
- module: options.isUsingTsSolutionConfig
804
- ? './dist/index.js'
805
- : './index.js',
806
- };
838
+ if (options.isUsingTsSolutionConfig) {
839
+ // the rollup configuration generator already handles this
840
+ return {};
841
+ }
842
+ else {
843
+ return {
844
+ // Since we're publishing both formats, skip the type field.
845
+ // Bundlers or Node will determine the entry point to use.
846
+ main: './index.cjs',
847
+ module: './index.js',
848
+ };
849
+ }
807
850
  case 'vite':
808
- return {
809
- type: 'module',
810
- main: options.isUsingTsSolutionConfig
811
- ? './dist/index.js'
812
- : './index.js',
813
- typings: options.isUsingTsSolutionConfig
814
- ? './dist/index.d.ts'
815
- : './index.d.ts',
816
- };
851
+ if (options.isUsingTsSolutionConfig) {
852
+ // the vite configuration generator already handle this
853
+ return {};
854
+ }
855
+ else {
856
+ return {
857
+ type: 'module',
858
+ main: './index.js',
859
+ types: './index.d.ts',
860
+ };
861
+ }
817
862
  case 'esbuild':
818
- // For libraries intended for Node, use CJS.
819
- return {
820
- type: 'commonjs',
821
- main: options.isUsingTsSolutionConfig
822
- ? './dist/index.cjs'
823
- : './index.cjs',
824
- typings: options.isUsingTsSolutionConfig
825
- ? './dist/index.d.ts'
826
- : './index.d.ts',
827
- };
828
- default: {
863
+ if (options.isUsingTsSolutionConfig) {
864
+ return {
865
+ type: 'module',
866
+ main: './dist/index.js',
867
+ types: './dist/index.d.ts',
868
+ };
869
+ }
870
+ else {
871
+ return {
872
+ type: 'commonjs',
873
+ main: './index.cjs',
874
+ types: './index.d.ts',
875
+ };
876
+ }
877
+ case 'none': {
878
+ if (options.isUsingTsSolutionConfig) {
879
+ return {
880
+ main: options.js ? './src/index.js' : './src/index.ts',
881
+ types: options.js ? './src/index.js' : './src/index.ts',
882
+ exports: {
883
+ '.': options.js
884
+ ? './src/index.js'
885
+ : {
886
+ types: './src/index.ts',
887
+ import: './src/index.ts',
888
+ default: './src/index.ts',
889
+ },
890
+ './package.json': './package.json',
891
+ },
892
+ };
893
+ }
829
894
  return {
830
895
  // Safest option is to not set a type field.
831
896
  // Allow the user to decide which module format their library is using
832
897
  type: undefined,
833
- // For non-buildable libraries, point to source so we can still use them in apps via bundlers like Vite.
834
- main: options.isUsingTsSolutionConfig
835
- ? options.js
836
- ? './src/index.js'
837
- : './src/index.ts'
838
- : undefined,
839
- types: options.isUsingTsSolutionConfig
840
- ? options.js
841
- ? './src/index.js'
842
- : './src/index.ts'
843
- : undefined,
844
898
  };
845
899
  }
900
+ default: {
901
+ return {};
902
+ }
846
903
  }
847
904
  }
848
905
  function projectsConfigMatchesProject(projectsConfig, project) {
@@ -33,7 +33,6 @@ export interface LibraryGeneratorSchema {
33
33
  simpleName?: boolean;
34
34
  addPlugin?: boolean;
35
35
  useProjectJson?: boolean;
36
- skipWorkspacesWarning?: boolean;
37
36
  useTscExecutor?: boolean;
38
37
  }
39
38
 
@@ -47,5 +46,4 @@ export interface NormalizedLibraryGeneratorOptions
47
46
  importPath?: string;
48
47
  hasPlugin: boolean;
49
48
  isUsingTsSolutionConfig: boolean;
50
- projectPackageManagerWorkspaceState: ProjectPackageManagerWorkspaceState;
51
49
  }
@@ -98,7 +98,7 @@ async function setupBuildGenerator(tree, options) {
98
98
  project: options.project,
99
99
  skipFormat: true,
100
100
  skipValidation: true,
101
- format: ['cjs'],
101
+ format: isTsSolutionSetup ? ['esm'] : ['cjs'],
102
102
  });
103
103
  tasks.push(task);
104
104
  break;
@@ -111,7 +111,7 @@ async function setupBuildGenerator(tree, options) {
111
111
  tsConfig: tsConfigFile,
112
112
  project: options.project,
113
113
  compiler: 'tsc',
114
- format: ['cjs', 'esm'],
114
+ format: isTsSolutionSetup ? ['esm'] : ['cjs', 'esm'],
115
115
  addPlugin,
116
116
  skipFormat: true,
117
117
  skipValidation: true,
@@ -165,7 +165,7 @@ async function setupBuildGenerator(tree, options) {
165
165
  }
166
166
  (0, devkit_1.updateProjectConfiguration)(tree, options.project, project);
167
167
  tasks.push((0, add_swc_dependencies_1.addSwcDependencies)(tree));
168
- (0, add_swc_config_1.addSwcConfig)(tree, project.root, 'commonjs');
168
+ (0, add_swc_config_1.addSwcConfig)(tree, project.root, isTsSolutionSetup ? 'es6' : 'commonjs');
169
169
  if (isTsSolutionSetup) {
170
170
  updatePackageJsonForSwc(tree, options, project);
171
171
  }
@@ -199,8 +199,9 @@ function updateTsConfigReferences(tree, tsSysFromTree, tsconfigInfoCaches, tsCon
199
199
  }
200
200
  let hasChanges = false;
201
201
  for (const dep of dependencies) {
202
- // Ensure the project reference for the target is set
203
- let referencePath = dep.data.root;
202
+ // Ensure the project reference for the target is set if we can find the
203
+ // relevant tsconfig file
204
+ let referencePath;
204
205
  if (runtimeTsConfigFileName) {
205
206
  const runtimeTsConfigPath = (0, devkit_1.joinPathFragments)(dep.data.root, runtimeTsConfigFileName);
206
207
  if (tsconfigExists(tree, tsconfigInfoCaches, runtimeTsConfigPath)) {
@@ -233,6 +234,14 @@ function updateTsConfigReferences(tree, tsSysFromTree, tsconfigInfoCaches, tsCon
233
234
  continue;
234
235
  }
235
236
  }
237
+ if (!referencePath) {
238
+ if (tsconfigExists(tree, tsconfigInfoCaches, (0, devkit_1.joinPathFragments)(dep.data.root, 'tsconfig.json'))) {
239
+ referencePath = dep.data.root;
240
+ }
241
+ else {
242
+ continue;
243
+ }
244
+ }
236
245
  const relativePathToTargetRoot = (0, posix_1.relative)(projectRoot, referencePath);
237
246
  if (!newReferencesSet.has(relativePathToTargetRoot)) {
238
247
  newReferencesSet.add(relativePathToTargetRoot);
@@ -270,7 +279,7 @@ function collectProjectDependencies(tree, projectName, projectGraph, collectedDe
270
279
  .some((d) => d.name === targetProjectNode.name)) {
271
280
  collectedDependencies.get(projectName).push(targetProjectNode);
272
281
  }
273
- if (process.env.NX_DISABLE_TS_SYNC_TRANSITIVE_DEPENDENCIES === 'true') {
282
+ if (process.env.NX_ENABLE_TS_SYNC_TRANSITIVE_DEPENDENCIES !== 'true') {
274
283
  continue;
275
284
  }
276
285
  // Recursively get the dependencies of the target project
@@ -94,6 +94,10 @@ async function createNodesInternal(configFilePath, options, context, lockFileNam
94
94
  const extendedConfigFiles = getExtendedConfigFiles(fullConfigPath, tsConfig);
95
95
  const internalReferencedFiles = resolveInternalProjectReferences(tsConfig, context.workspaceRoot, projectRoot);
96
96
  const externalProjectReferences = resolveShallowExternalProjectReferences(tsConfig, context.workspaceRoot, projectRoot);
97
+ const packageJsonPath = (0, devkit_1.joinPathFragments)(projectRoot, 'package.json');
98
+ const packageJson = (0, node_fs_1.existsSync)(packageJsonPath)
99
+ ? (0, devkit_1.readJsonFile)(packageJsonPath)
100
+ : null;
97
101
  const nodeHash = (0, file_hasher_1.hashArray)([
98
102
  ...[
99
103
  fullConfigPath,
@@ -103,6 +107,7 @@ async function createNodesInternal(configFilePath, options, context, lockFileNam
103
107
  (0, node_path_1.join)(context.workspaceRoot, lockFileName),
104
108
  ].map(file_hasher_1.hashFile),
105
109
  (0, file_hasher_1.hashObject)(options),
110
+ ...(packageJson ? [(0, file_hasher_1.hashObject)(packageJson)] : []),
106
111
  ]);
107
112
  const cacheKey = `${nodeHash}_${configFilePath}`;
108
113
  targetsCache[cacheKey] ??= buildTscTargets(fullConfigPath, projectRoot, options, context);
@@ -163,7 +168,7 @@ function buildTscTargets(configFilePath, projectRoot, options, context) {
163
168
  // Build target
164
169
  if (options.build &&
165
170
  (0, node_path_1.basename)(configFilePath) === options.build.configName &&
166
- isValidPackageJsonBuildConfig(tsConfig, context.workspaceRoot, projectRoot, configFilePath)) {
171
+ isValidPackageJsonBuildConfig(tsConfig, context.workspaceRoot, projectRoot)) {
167
172
  internalProjectReferences ??= resolveInternalProjectReferences(tsConfig, context.workspaceRoot, projectRoot);
168
173
  const targetName = options.build.targetName;
169
174
  targets[targetName] = {
@@ -230,6 +235,9 @@ function getInputs(namedInputs, configFilePath, tsConfig, internalProjectReferen
230
235
  });
231
236
  const inputs = [];
232
237
  if (includePaths.size) {
238
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(workspaceRoot, projectRoot, 'package.json'))) {
239
+ inputs.push('{projectRoot}/package.json');
240
+ }
233
241
  inputs.push(...Array.from(configFiles).map((p) => pathToInputOrOutput(p, workspaceRoot, projectRoot)), ...Array.from(includePaths).map((p) => pathToInputOrOutput((0, devkit_1.joinPathFragments)(projectRoot, p), workspaceRoot, projectRoot)));
234
242
  }
235
243
  else {
@@ -310,49 +318,45 @@ function getOutputs(configFilePath, tsConfig, internalProjectReferences, workspa
310
318
  return Array.from(outputs);
311
319
  }
312
320
  /**
313
- * Checks whether a `package.json` file has a valid build configuration by ensuring
314
- * that the `main`, `module`, or `exports` do not include paths from the `rootDir`.
315
- * Or if `outFile` is defined, it should not be within the `rootDir`.
321
+ * Validates the build configuration of a `package.json` file by ensuring that paths in the `exports`, `module`,
322
+ * and `main` fields reference valid output paths within the `outDir` defined in the TypeScript configuration.
323
+ * Priority is given to the `exports` field, specifically the `.` export if defined. If `exports` is not defined,
324
+ * the function falls back to validating `main` and `module` fields. If `outFile` is specified, it validates that the file
325
+ * is located within the output directory.
326
+ * If no `package.json` file exists, it assumes the configuration is valid.
316
327
  *
317
328
  * @param tsConfig The TypeScript configuration object.
318
329
  * @param workspaceRoot The workspace root path.
319
330
  * @param projectRoot The project root path.
320
- * @param tsConfigPath The path to the TypeScript configuration file.
321
331
  * @returns `true` if the package has a valid build configuration; otherwise, `false`.
322
332
  */
323
- function isValidPackageJsonBuildConfig(tsConfig, workspaceRoot, projectRoot, tsConfigPath) {
324
- if (!(0, node_fs_1.existsSync)((0, devkit_1.joinPathFragments)(projectRoot, 'package.json'))) {
333
+ function isValidPackageJsonBuildConfig(tsConfig, workspaceRoot, projectRoot) {
334
+ const packageJsonPath = (0, node_path_1.join)(workspaceRoot, projectRoot, 'package.json');
335
+ if (!(0, node_fs_1.existsSync)(packageJsonPath)) {
325
336
  // If the package.json file does not exist.
326
337
  // Assume it's valid because it would be using `project.json` instead.
327
338
  return true;
328
339
  }
329
- const packageJson = (0, devkit_1.readJsonFile)((0, devkit_1.joinPathFragments)(projectRoot, 'package.json'));
330
- const rootDir = tsConfig.options.rootDir ?? 'src/';
331
- if (!tsConfig.options.rootDir) {
332
- console.warn(`The 'rootDir' option is not set in the tsconfig file at ${tsConfigPath}. Assuming 'src/' as the root directory.`);
333
- }
334
- const isPathWithinSrc = (path) => {
335
- const resolvedRootDir = (0, node_path_1.resolve)(workspaceRoot, projectRoot, rootDir);
336
- const pathToCheck = (0, node_path_1.resolve)(workspaceRoot, projectRoot, path);
337
- return pathToCheck.startsWith(resolvedRootDir);
338
- };
339
- // If `outFile` is defined, check the validity of the path.
340
- if (tsConfig.options.outFile) {
341
- if (isPathWithinSrc(tsConfig.options.outFile)) {
342
- return false;
343
- }
344
- }
345
- const buildPaths = ['main', 'module'];
346
- for (const field of buildPaths) {
347
- if (packageJson[field] && isPathWithinSrc(packageJson[field])) {
348
- return false;
340
+ const packageJson = (0, devkit_1.readJsonFile)(packageJsonPath);
341
+ const outDir = tsConfig.options.outFile
342
+ ? (0, node_path_1.dirname)(tsConfig.options.outFile)
343
+ : tsConfig.options.outDir;
344
+ const resolvedOutDir = outDir
345
+ ? (0, node_path_1.resolve)(workspaceRoot, projectRoot, outDir)
346
+ : undefined;
347
+ const isPathSourceFile = (path) => {
348
+ if (resolvedOutDir) {
349
+ const pathToCheck = (0, node_path_1.resolve)(workspaceRoot, projectRoot, path);
350
+ return !pathToCheck.startsWith(resolvedOutDir);
349
351
  }
350
- }
351
- const exports = packageJson?.exports;
352
+ const ext = (0, node_path_1.extname)(path);
353
+ // Check that the file extension is a TS file extension. As the source files are in the same directory as the output files.
354
+ return ['.ts', '.tsx', '.cts', '.mts'].includes(ext);
355
+ };
352
356
  // Checks if the value is a path within the `src` directory.
353
357
  const containsInvalidPath = (value) => {
354
358
  if (typeof value === 'string') {
355
- return isPathWithinSrc(value);
359
+ return isPathSourceFile(value);
356
360
  }
357
361
  else if (typeof value === 'object') {
358
362
  return Object.entries(value).some(([currentKey, subValue]) => {
@@ -361,30 +365,45 @@ function isValidPackageJsonBuildConfig(tsConfig, workspaceRoot, projectRoot, tsC
361
365
  return false;
362
366
  }
363
367
  if (typeof subValue === 'string') {
364
- return isPathWithinSrc(subValue);
368
+ return isPathSourceFile(subValue);
365
369
  }
366
370
  return false;
367
371
  });
368
372
  }
369
373
  return false;
370
374
  };
371
- if (typeof exports === 'string' && isPathWithinSrc(exports)) {
372
- return false;
373
- }
374
- // Check nested exports if `exports` is an object.
375
- if (typeof exports === 'object') {
375
+ const exports = packageJson?.exports;
376
+ // Check the `.` export if `exports` is defined.
377
+ if (exports) {
378
+ if (typeof exports === 'string') {
379
+ return !isPathSourceFile(exports);
380
+ }
381
+ if (typeof exports === 'object' && '.' in exports) {
382
+ return !containsInvalidPath(exports['.']);
383
+ }
384
+ // Check other exports if `.` is not defined or valid.
376
385
  for (const key in exports) {
377
- if (containsInvalidPath(exports[key])) {
386
+ if (key !== '.' && containsInvalidPath(exports[key])) {
378
387
  return false;
379
388
  }
380
389
  }
390
+ return true;
391
+ }
392
+ // If `exports` is not defined, fallback to `main` and `module` fields.
393
+ const buildPaths = ['main', 'module'];
394
+ for (const field of buildPaths) {
395
+ if (packageJson[field] && isPathSourceFile(packageJson[field])) {
396
+ return false;
397
+ }
381
398
  }
382
399
  return true;
383
400
  }
384
401
  function pathToInputOrOutput(path, workspaceRoot, projectRoot) {
385
- const pathRelativeToProjectRoot = (0, devkit_1.normalizePath)((0, node_path_1.relative)(projectRoot, path));
402
+ const fullProjectRoot = (0, node_path_1.resolve)(workspaceRoot, projectRoot);
403
+ const fullPath = (0, node_path_1.resolve)(workspaceRoot, path);
404
+ const pathRelativeToProjectRoot = (0, devkit_1.normalizePath)((0, node_path_1.relative)(fullProjectRoot, fullPath));
386
405
  if (pathRelativeToProjectRoot.startsWith('..')) {
387
- return (0, devkit_1.joinPathFragments)('{workspaceRoot}', (0, node_path_1.relative)(workspaceRoot, path));
406
+ return (0, devkit_1.joinPathFragments)('{workspaceRoot}', (0, node_path_1.relative)(workspaceRoot, fullPath));
388
407
  }
389
408
  return (0, devkit_1.joinPathFragments)('{projectRoot}', pathRelativeToProjectRoot);
390
409
  }
@@ -0,0 +1,2 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ export declare function sortPackageJsonFields(tree: Tree, projectRoot: string): void;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sortPackageJsonFields = sortPackageJsonFields;
4
+ const devkit_1 = require("@nx/devkit");
5
+ function sortPackageJsonFields(tree, projectRoot) {
6
+ const packageJsonPath = (0, devkit_1.joinPathFragments)(projectRoot, 'package.json');
7
+ if (!tree.exists(packageJsonPath))
8
+ return;
9
+ (0, devkit_1.updateJson)(tree, packageJsonPath, (json) => {
10
+ // Note that these are fields that our generators may use, so it's not exhaustive.
11
+ const orderedTopFields = new Set([
12
+ 'name',
13
+ 'version',
14
+ 'private',
15
+ 'description',
16
+ 'type',
17
+ 'main',
18
+ 'module',
19
+ 'types',
20
+ 'exports',
21
+ ]);
22
+ const orderedBottomFields = new Set([
23
+ 'dependencies',
24
+ 'devDependencies',
25
+ 'peerDependencies',
26
+ 'optionalDependencies',
27
+ ]);
28
+ const otherFields = new Set(Object.keys(json).filter((k) => !orderedTopFields.has(k) && !orderedBottomFields.has(k)));
29
+ const allFields = [
30
+ ...orderedTopFields,
31
+ ...otherFields,
32
+ ...orderedBottomFields,
33
+ ];
34
+ const sortedJson = {};
35
+ for (const k of allFields) {
36
+ sortedJson[k] = json[k];
37
+ }
38
+ return sortedJson;
39
+ });
40
+ }
@@ -181,6 +181,9 @@ function getUpdatedPackageJsonContent(packageJson, options) {
181
181
  }
182
182
  else if (typeof packageJson.exports[exportEntry] === 'object') {
183
183
  packageJson.exports[exportEntry].import ??= filePath;
184
+ if (!hasCjsFormat) {
185
+ packageJson.exports[exportEntry].default ??= filePath;
186
+ }
184
187
  }
185
188
  }
186
189
  }
@@ -52,6 +52,9 @@ function getTypeCheckOptions(normalizedOptions) {
52
52
  typeCheckOptions.incremental = true;
53
53
  typeCheckOptions.cacheDir = devkit_1.cacheDir;
54
54
  }
55
+ if (normalizedOptions.isTsSolutionSetup && normalizedOptions.skipTypeCheck) {
56
+ typeCheckOptions.ignoreDiagnostics = true;
57
+ }
55
58
  return typeCheckOptions;
56
59
  }
57
60
  async function compileSwc(context, normalizedOptions, postCompilationCallback) {
@@ -59,16 +62,25 @@ async function compileSwc(context, normalizedOptions, postCompilationCallback) {
59
62
  if (normalizedOptions.clean) {
60
63
  (0, node_fs_1.rmSync)(normalizedOptions.outputPath, { recursive: true, force: true });
61
64
  }
62
- const swcCmdLog = (0, node_child_process_1.execSync)(getSwcCmd(normalizedOptions), {
63
- encoding: 'utf8',
64
- cwd: normalizedOptions.swcCliOptions.swcCwd,
65
- windowsHide: false,
66
- });
67
- devkit_1.logger.log(swcCmdLog.replace(/\n/, ''));
68
- const isCompileSuccess = swcCmdLog.includes('Successfully compiled');
69
- if (normalizedOptions.skipTypeCheck || normalizedOptions.isTsSolutionSetup) {
65
+ try {
66
+ const swcCmdLog = (0, node_child_process_1.execSync)(getSwcCmd(normalizedOptions), {
67
+ encoding: 'utf8',
68
+ cwd: normalizedOptions.swcCliOptions.swcCwd,
69
+ windowsHide: false,
70
+ stdio: 'pipe',
71
+ });
72
+ devkit_1.logger.log(swcCmdLog.replace(/\n/, ''));
73
+ }
74
+ catch (error) {
75
+ devkit_1.logger.error('SWC compilation failed');
76
+ if (error.stderr) {
77
+ devkit_1.logger.error(error.stderr.toString());
78
+ }
79
+ return { success: false };
80
+ }
81
+ if (normalizedOptions.skipTypeCheck && !normalizedOptions.isTsSolutionSetup) {
70
82
  await postCompilationCallback();
71
- return { success: isCompileSuccess };
83
+ return { success: true };
72
84
  }
73
85
  const { errors, warnings } = await (0, run_type_check_1.runTypeCheck)(getTypeCheckOptions(normalizedOptions));
74
86
  const hasErrors = errors.length > 0;
@@ -78,7 +90,7 @@ async function compileSwc(context, normalizedOptions, postCompilationCallback) {
78
90
  }
79
91
  await postCompilationCallback();
80
92
  return {
81
- success: !hasErrors && isCompileSuccess,
93
+ success: !hasErrors,
82
94
  outfile: normalizedOptions.mainOutputPath,
83
95
  };
84
96
  }
@@ -14,6 +14,7 @@ interface BaseTypeCheckOptions {
14
14
  incremental?: boolean;
15
15
  rootDir?: string;
16
16
  projectRoot?: string;
17
+ ignoreDiagnostics?: boolean;
17
18
  }
18
19
  type Mode = NoEmitMode | EmitDeclarationOnlyMode;
19
20
  interface NoEmitMode {
@@ -18,7 +18,9 @@ async function runTypeCheckWatch(options, callback) {
18
18
  };
19
19
  const watchProgram = ts.createWatchProgram(host);
20
20
  const program = watchProgram.getProgram().getProgram();
21
- const diagnostics = ts.getPreEmitDiagnostics(program);
21
+ const diagnostics = options.ignoreDiagnostics
22
+ ? []
23
+ : ts.getPreEmitDiagnostics(program);
22
24
  return {
23
25
  close: watchProgram.close.bind(watchProgram),
24
26
  preEmitErrors: diagnostics
@@ -48,9 +50,9 @@ async function runTypeCheck(options) {
48
50
  program = ts.createProgram(config.fileNames, compilerOptions);
49
51
  }
50
52
  const result = program.emit();
51
- const allDiagnostics = ts
52
- .getPreEmitDiagnostics(program)
53
- .concat(result.diagnostics);
53
+ const allDiagnostics = options.ignoreDiagnostics
54
+ ? []
55
+ : ts.getPreEmitDiagnostics(program).concat(result.diagnostics);
54
56
  return getTypeCheckResult(ts, allDiagnostics, workspaceRoot, config.fileNames.length, program.getSourceFiles().length, incremental);
55
57
  }
56
58
  async function setupTypeScript(options) {
@@ -7,9 +7,9 @@ exports.findRuntimeTsConfigName = findRuntimeTsConfigName;
7
7
  exports.updateTsconfigFiles = updateTsconfigFiles;
8
8
  exports.addProjectToTsSolutionWorkspace = addProjectToTsSolutionWorkspace;
9
9
  const devkit_1 = require("@nx/devkit");
10
+ const posix_1 = require("node:path/posix");
10
11
  const tree_1 = require("nx/src/generators/tree");
11
12
  const package_manager_workspaces_1 = require("../package-manager-workspaces");
12
- const posix_1 = require("node:path/posix");
13
13
  function isUsingTypeScriptPlugin(tree) {
14
14
  const nxJson = (0, devkit_1.readNxJson)(tree);
15
15
  return (nxJson?.plugins?.some((p) => typeof p === 'string'
@@ -44,7 +44,7 @@ function isWorkspaceSetupWithTsSolution(tree) {
44
44
  const baseTsconfigJson = (0, devkit_1.readJson)(tree, 'tsconfig.base.json');
45
45
  if (!baseTsconfigJson.compilerOptions ||
46
46
  !baseTsconfigJson.compilerOptions.composite ||
47
- !baseTsconfigJson.compilerOptions.declaration) {
47
+ baseTsconfigJson.compilerOptions.declaration === false) {
48
48
  return false;
49
49
  }
50
50
  const { compilerOptions, ...rest } = baseTsconfigJson;
@@ -139,17 +139,16 @@ function updateTsconfigFiles(tree, projectRoot, runtimeTsconfigFileName, compile
139
139
  }
140
140
  }
141
141
  function addProjectToTsSolutionWorkspace(tree, projectDir) {
142
- // If dir is "libs/foo" then use "libs/**" so we don't need so many entries in the workspace file.
142
+ // If dir is "libs/foo" then use "libs/*" so we don't need so many entries in the workspace file.
143
+ // If dir is nested like "libs/shared/foo" then we add "libs/shared/*".
143
144
  // If the dir is just "foo" then we have to add it as is.
144
145
  const baseDir = (0, posix_1.dirname)(projectDir);
145
- const pattern = baseDir === '.' ? projectDir : `${baseDir}/**`;
146
+ const pattern = baseDir === '.' ? projectDir : `${baseDir}/*`;
146
147
  if (tree.exists('pnpm-workspace.yaml')) {
147
148
  const { load, dump } = require('@zkochan/js-yaml');
148
149
  const workspaceFile = tree.read('pnpm-workspace.yaml', 'utf-8');
149
- const yamlData = load(workspaceFile);
150
- if (!yamlData?.packages) {
151
- yamlData.packages = [];
152
- }
150
+ const yamlData = load(workspaceFile) ?? {};
151
+ yamlData.packages ??= [];
153
152
  if (!yamlData.packages.includes(pattern)) {
154
153
  yamlData.packages.push(pattern);
155
154
  tree.write('pnpm-workspace.yaml', dump(yamlData, { indent: 2, quotingType: '"', forceQuotes: true }));