@nx/webpack 17.0.3 → 17.0.5

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.
Files changed (81) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +9 -4
  3. package/generators.json +2 -2
  4. package/index.d.ts +3 -1
  5. package/index.js +7 -2
  6. package/migrations.json +6 -0
  7. package/package.json +6 -5
  8. package/plugin.d.ts +1 -0
  9. package/plugin.js +5 -0
  10. package/src/executors/dev-server/dev-server.impl.js +31 -17
  11. package/src/executors/dev-server/lib/get-dev-server-config.d.ts +2 -3
  12. package/src/executors/dev-server/lib/get-dev-server-config.js +18 -26
  13. package/src/executors/dev-server/schema.d.ts +8 -8
  14. package/src/executors/webpack/lib/normalize-options.d.ts +1 -2
  15. package/src/executors/webpack/lib/normalize-options.js +9 -53
  16. package/src/executors/webpack/schema.d.ts +10 -7
  17. package/src/executors/webpack/schema.json +30 -50
  18. package/src/executors/webpack/webpack.impl.js +36 -16
  19. package/src/generators/configuration/configuration.d.ts +3 -2
  20. package/src/generators/configuration/configuration.js +95 -23
  21. package/src/generators/configuration/schema.d.ts +1 -0
  22. package/src/generators/configuration/schema.json +1 -1
  23. package/src/generators/init/init.d.ts +1 -0
  24. package/src/generators/init/init.js +48 -23
  25. package/src/generators/init/schema.d.ts +4 -2
  26. package/src/generators/init/schema.json +18 -13
  27. package/src/migrations/update-17-2-1/webpack-config-setup.d.ts +2 -0
  28. package/src/migrations/update-17-2-1/webpack-config-setup.js +31 -0
  29. package/src/plugins/generate-package-json-plugin.d.ts +6 -4
  30. package/src/plugins/generate-package-json-plugin.js +11 -14
  31. package/src/plugins/nx-typescript-webpack-plugin/nx-tsconfig-paths-webpack-plugin.d.ts +8 -0
  32. package/src/plugins/nx-typescript-webpack-plugin/nx-tsconfig-paths-webpack-plugin.js +31 -0
  33. package/src/plugins/nx-webpack-plugin/lib/apply-base-config.d.ts +5 -0
  34. package/src/plugins/nx-webpack-plugin/lib/apply-base-config.js +318 -0
  35. package/src/plugins/nx-webpack-plugin/lib/apply-web-config.d.ts +5 -0
  36. package/src/plugins/nx-webpack-plugin/lib/apply-web-config.js +372 -0
  37. package/src/plugins/nx-webpack-plugin/lib/compiler-loaders.d.ts +53 -0
  38. package/src/plugins/nx-webpack-plugin/lib/compiler-loaders.js +78 -0
  39. package/src/plugins/nx-webpack-plugin/lib/get-terser-ecma-version.d.ts +1 -0
  40. package/src/plugins/nx-webpack-plugin/lib/get-terser-ecma-version.js +35 -0
  41. package/src/plugins/nx-webpack-plugin/lib/instantiate-script-plugins.d.ts +3 -0
  42. package/src/plugins/nx-webpack-plugin/lib/instantiate-script-plugins.js +42 -0
  43. package/src/plugins/nx-webpack-plugin/lib/normalize-options.d.ts +4 -0
  44. package/src/plugins/nx-webpack-plugin/lib/normalize-options.js +148 -0
  45. package/src/plugins/nx-webpack-plugin/lib/stylesheet-loaders.d.ts +73 -0
  46. package/src/plugins/nx-webpack-plugin/lib/stylesheet-loaders.js +117 -0
  47. package/src/plugins/nx-webpack-plugin/nx-webpack-plugin-options.d.ts +216 -0
  48. package/src/plugins/nx-webpack-plugin/nx-webpack-plugin-options.js +2 -0
  49. package/src/plugins/nx-webpack-plugin/nx-webpack-plugin.d.ts +17 -0
  50. package/src/plugins/nx-webpack-plugin/nx-webpack-plugin.js +48 -0
  51. package/src/plugins/plugin.d.ts +9 -0
  52. package/src/plugins/plugin.js +132 -0
  53. package/src/utils/config.d.ts +11 -6
  54. package/src/utils/config.js +48 -13
  55. package/src/utils/ensure-dependencies.d.ts +6 -0
  56. package/src/utils/ensure-dependencies.js +27 -0
  57. package/src/utils/get-client-environment.js +4 -1
  58. package/src/utils/has-plugin.d.ts +2 -0
  59. package/src/utils/has-plugin.js +11 -0
  60. package/src/utils/module-federation/dependencies.js +15 -3
  61. package/src/utils/module-federation/get-remotes-for-host.d.ts +2 -1
  62. package/src/utils/module-federation/get-remotes-for-host.js +11 -7
  63. package/src/utils/module-federation/remotes.js +1 -1
  64. package/src/utils/module-federation/secondary-entry-points.js +1 -1
  65. package/src/utils/module-federation/typescript.js +14 -9
  66. package/src/utils/versions.d.ts +1 -1
  67. package/src/utils/versions.js +2 -2
  68. package/src/utils/webpack/deprecated-stylus-loader.js +2 -2
  69. package/src/utils/webpack/interpolate-env-variables-to-index.js +4 -1
  70. package/src/utils/webpack/plugins/postcss-cli-resources.js +2 -2
  71. package/src/utils/webpack/read-webpack-options.d.ts +10 -0
  72. package/src/utils/webpack/read-webpack-options.js +41 -0
  73. package/src/utils/webpack/resolve-user-defined-webpack-config.d.ts +3 -0
  74. package/src/utils/webpack/{custom-webpack.js → resolve-user-defined-webpack-config.js} +14 -8
  75. package/src/utils/with-nx.d.ts +4 -58
  76. package/src/utils/with-nx.js +22 -362
  77. package/src/utils/with-web.d.ts +2 -2
  78. package/src/utils/with-web.js +9 -488
  79. package/src/executors/webpack/lib/get-webpack-config.d.ts +0 -5
  80. package/src/executors/webpack/lib/get-webpack-config.js +0 -16
  81. package/src/utils/webpack/custom-webpack.d.ts +0 -2
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNodes = exports.createDependencies = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const path_1 = require("path");
6
+ const get_named_inputs_1 = require("@nx/devkit/src/utils/get-named-inputs");
7
+ const fs_1 = require("fs");
8
+ const read_webpack_options_1 = require("../utils/webpack/read-webpack-options");
9
+ const resolve_user_defined_webpack_config_1 = require("../utils/webpack/resolve-user-defined-webpack-config");
10
+ const js_1 = require("@nx/js");
11
+ const cache_directory_1 = require("nx/src/utils/cache-directory");
12
+ const calculate_hash_for_create_nodes_1 = require("@nx/devkit/src/utils/calculate-hash-for-create-nodes");
13
+ const cachePath = (0, path_1.join)(cache_directory_1.projectGraphCacheDirectory, 'webpack.hash');
14
+ const targetsCache = (0, fs_1.existsSync)(cachePath) ? readTargetsCache() : {};
15
+ const calculatedTargets = {};
16
+ function readTargetsCache() {
17
+ return (0, devkit_1.readJsonFile)(cachePath);
18
+ }
19
+ function writeTargetsToCache(targets) {
20
+ (0, devkit_1.writeJsonFile)(cachePath, targets);
21
+ }
22
+ const createDependencies = () => {
23
+ writeTargetsToCache(calculatedTargets);
24
+ return [];
25
+ };
26
+ exports.createDependencies = createDependencies;
27
+ exports.createNodes = [
28
+ '**/webpack.config.{js,ts,mjs,cjs}',
29
+ async (configFilePath, options, context) => {
30
+ options ??= {};
31
+ options.buildTargetName ??= 'build';
32
+ options.serveTargetName ??= 'serve';
33
+ options.serveStaticTargetName ??= 'serve-static';
34
+ options.previewTargetName ??= 'preview';
35
+ const projectRoot = (0, path_1.dirname)(configFilePath);
36
+ // Do not create a project if package.json and project.json isn't there.
37
+ const siblingFiles = (0, fs_1.readdirSync)((0, path_1.join)(context.workspaceRoot, projectRoot));
38
+ if (!siblingFiles.includes('package.json') &&
39
+ !siblingFiles.includes('project.json')) {
40
+ return {};
41
+ }
42
+ const hash = (0, calculate_hash_for_create_nodes_1.calculateHashForCreateNodes)(projectRoot, options, context, [
43
+ (0, js_1.getLockFileName)((0, devkit_1.detectPackageManager)(context.workspaceRoot)),
44
+ ]);
45
+ const targets = targetsCache[hash]
46
+ ? targetsCache[hash]
47
+ : await createWebpackTargets(configFilePath, projectRoot, options, context);
48
+ return {
49
+ projects: {
50
+ [projectRoot]: {
51
+ projectType: 'application',
52
+ targets,
53
+ },
54
+ },
55
+ };
56
+ },
57
+ ];
58
+ async function createWebpackTargets(configFilePath, projectRoot, options, context) {
59
+ const namedInputs = (0, get_named_inputs_1.getNamedInputs)(projectRoot, context);
60
+ const webpackConfig = (0, resolve_user_defined_webpack_config_1.resolveUserDefinedWebpackConfig)((0, path_1.join)(context.workspaceRoot, configFilePath), (0, js_1.getRootTsConfigPath)(), true);
61
+ const webpackOptions = await (0, read_webpack_options_1.readWebpackOptions)(webpackConfig);
62
+ const outputPath = normalizeOutputPath(webpackOptions.output?.path, projectRoot);
63
+ const targets = {};
64
+ targets[options.buildTargetName] = {
65
+ command: `webpack-cli build`,
66
+ options: { cwd: projectRoot, args: ['--node-env=production'] },
67
+ cache: true,
68
+ dependsOn: [`^${options.buildTargetName}`],
69
+ inputs: 'production' in namedInputs
70
+ ? [
71
+ 'production',
72
+ '^production',
73
+ {
74
+ externalDependencies: ['webpack-cli'],
75
+ },
76
+ ]
77
+ : [
78
+ 'default',
79
+ '^default',
80
+ {
81
+ externalDependencies: ['webpack-cli'],
82
+ },
83
+ ],
84
+ outputs: [outputPath],
85
+ };
86
+ targets[options.serveTargetName] = {
87
+ command: `webpack-cli serve`,
88
+ options: {
89
+ cwd: projectRoot,
90
+ args: ['--node-env=development'],
91
+ },
92
+ };
93
+ targets[options.previewTargetName] = {
94
+ command: `webpack-cli serve`,
95
+ options: {
96
+ cwd: projectRoot,
97
+ args: ['--node-env=production'],
98
+ },
99
+ };
100
+ targets[options.serveStaticTargetName] = {
101
+ executor: '@nx/web:file-server',
102
+ options: {
103
+ buildTarget: options.buildTargetName,
104
+ spa: true,
105
+ },
106
+ };
107
+ return targets;
108
+ }
109
+ function normalizeOutputPath(outputPath, projectRoot) {
110
+ if (!outputPath) {
111
+ // If outputPath is undefined, use webpack's default `dist` directory.
112
+ if (projectRoot === '.') {
113
+ return `{projectRoot}/dist}`;
114
+ }
115
+ else {
116
+ return `{workspaceRoot}/dist/{projectRoot}`;
117
+ }
118
+ }
119
+ else {
120
+ if ((0, path_1.isAbsolute)(outputPath)) {
121
+ return `{workspaceRoot}/${(0, path_1.relative)(devkit_1.workspaceRoot, outputPath)}`;
122
+ }
123
+ else {
124
+ if (outputPath.startsWith('..')) {
125
+ return (0, path_1.join)('{workspaceRoot}', (0, path_1.join)(projectRoot, outputPath));
126
+ }
127
+ else {
128
+ return (0, path_1.join)('{projectRoot}', outputPath);
129
+ }
130
+ }
131
+ }
132
+ }
@@ -1,17 +1,22 @@
1
1
  import { ExecutorContext } from '@nx/devkit';
2
2
  import { Configuration } from 'webpack';
3
3
  import { NormalizedWebpackExecutorOptions } from '../executors/webpack/schema';
4
- /** @deprecated use withNx and withWeb plugins directly */
5
- export declare function getBaseWebpackPartial(options: NormalizedWebpackExecutorOptions, context?: ExecutorContext): Configuration;
4
+ export declare const nxWebpackComposablePlugin = "nxWebpackComposablePlugin";
5
+ export declare function isNxWebpackComposablePlugin(a: unknown): a is AsyncNxComposableWebpackPlugin;
6
6
  export interface NxWebpackExecutionContext {
7
7
  options: NormalizedWebpackExecutorOptions;
8
8
  context: ExecutorContext;
9
+ configuration?: string;
9
10
  }
10
- export interface NxWebpackPlugin {
11
+ export interface NxComposableWebpackPlugin {
11
12
  (config: Configuration, ctx: NxWebpackExecutionContext): Configuration;
12
13
  }
13
- export interface AsyncNxWebpackPlugin {
14
+ export interface AsyncNxComposableWebpackPlugin {
14
15
  (config: Configuration, ctx: NxWebpackExecutionContext): Configuration | Promise<Configuration>;
15
16
  }
16
- export declare function composePlugins(...plugins: (NxWebpackPlugin | AsyncNxWebpackPlugin | Promise<NxWebpackPlugin | AsyncNxWebpackPlugin>)[]): (config: Configuration, ctx: NxWebpackExecutionContext) => Promise<Configuration>;
17
- export declare function composePluginsSync(...plugins: NxWebpackPlugin[]): (config: Configuration, ctx: NxWebpackExecutionContext) => Configuration;
17
+ export declare function composePlugins(...plugins: (NxComposableWebpackPlugin | AsyncNxComposableWebpackPlugin | Promise<NxComposableWebpackPlugin | AsyncNxComposableWebpackPlugin>)[]): ((config: Configuration, ctx: NxWebpackExecutionContext) => Promise<Configuration>) & {
18
+ nxWebpackComposablePlugin: boolean;
19
+ };
20
+ export declare function composePluginsSync(...plugins: NxComposableWebpackPlugin[]): ((config: Configuration, ctx: NxWebpackExecutionContext) => Configuration) & {
21
+ nxWebpackComposablePlugin: boolean;
22
+ };
@@ -1,31 +1,66 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.composePluginsSync = exports.composePlugins = exports.getBaseWebpackPartial = void 0;
4
- const with_nx_1 = require("./with-nx");
5
- const with_web_1 = require("./with-web");
6
- /** @deprecated use withNx and withWeb plugins directly */
7
- function getBaseWebpackPartial(options, context) {
8
- const config = {};
9
- const configure = composePluginsSync((0, with_nx_1.withNx)(), (0, with_web_1.withWeb)());
10
- return configure(config, { options, context });
3
+ exports.composePluginsSync = exports.composePlugins = exports.isNxWebpackComposablePlugin = exports.nxWebpackComposablePlugin = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ exports.nxWebpackComposablePlugin = 'nxWebpackComposablePlugin';
6
+ function isNxWebpackComposablePlugin(a) {
7
+ return a?.[exports.nxWebpackComposablePlugin] === true;
11
8
  }
12
- exports.getBaseWebpackPartial = getBaseWebpackPartial;
9
+ exports.isNxWebpackComposablePlugin = isNxWebpackComposablePlugin;
13
10
  function composePlugins(...plugins) {
14
- return async function combined(config, ctx) {
11
+ return Object.assign(async function combined(config, ctx) {
12
+ // Webpack may be calling us as a standard config function.
13
+ // Build up Nx context from environment variables.
14
+ // This is to enable `@nx/webpack/plugin` to work with existing projects.
15
+ if (ctx['env']) {
16
+ ensureNxWebpackExecutionContext(ctx);
17
+ // Build this from scratch since what webpack passes us is the env, not config,
18
+ // and `withNX()` creates a new config object anyway.
19
+ config = {};
20
+ }
15
21
  for (const plugin of plugins) {
16
22
  const fn = await plugin;
17
23
  config = await fn(config, ctx);
18
24
  }
19
25
  return config;
20
- };
26
+ }, {
27
+ [exports.nxWebpackComposablePlugin]: true,
28
+ });
21
29
  }
22
30
  exports.composePlugins = composePlugins;
23
31
  function composePluginsSync(...plugins) {
24
- return function combined(config, ctx) {
32
+ return Object.assign(function combined(config, ctx) {
25
33
  for (const plugin of plugins) {
26
34
  config = plugin(config, ctx);
27
35
  }
28
36
  return config;
29
- };
37
+ }, {
38
+ [exports.nxWebpackComposablePlugin]: true,
39
+ });
30
40
  }
31
41
  exports.composePluginsSync = composePluginsSync;
42
+ function ensureNxWebpackExecutionContext(ctx) {
43
+ const projectName = process.env.NX_TASK_TARGET_PROJECT;
44
+ const targetName = process.env.NX_TASK_TARGET_TARGET;
45
+ const configurationName = process.env.NX_TASK_TARGET_CONFIGURATION;
46
+ const projectGraph = (0, devkit_1.readCachedProjectGraph)();
47
+ const projectNode = projectGraph.nodes[projectName];
48
+ ctx.options ??= {
49
+ root: devkit_1.workspaceRoot,
50
+ projectRoot: projectNode.data.root,
51
+ sourceRoot: projectNode.data.sourceRoot ?? projectNode.data.root,
52
+ // These aren't actually needed since NxWebpackPlugin and withNx both support them being undefined.
53
+ assets: undefined,
54
+ outputPath: undefined,
55
+ tsConfig: undefined,
56
+ outputFileName: undefined,
57
+ };
58
+ ctx.context ??= {
59
+ projectName,
60
+ targetName,
61
+ configurationName,
62
+ cwd: process.cwd(),
63
+ root: devkit_1.workspaceRoot,
64
+ isVerbose: process.env['NX_VERBOSE_LOGGING'] === 'true',
65
+ };
66
+ }
@@ -0,0 +1,6 @@
1
+ import { type GeneratorCallback, type Tree } from '@nx/devkit';
2
+ export type EnsureDependenciesOptions = {
3
+ compiler?: 'swc' | 'tsc';
4
+ uiFramework?: 'none' | 'react';
5
+ };
6
+ export declare function ensureDependencies(tree: Tree, options: EnsureDependenciesOptions): GeneratorCallback;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ensureDependencies = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const add_swc_dependencies_1 = require("@nx/js/src/utils/swc/add-swc-dependencies");
6
+ const versions_1 = require("./versions");
7
+ function ensureDependencies(tree, options) {
8
+ const tasks = [];
9
+ const devDependencies = {};
10
+ if (options.compiler === 'swc') {
11
+ devDependencies['swc-loader'] = versions_1.swcLoaderVersion;
12
+ const addSwcTask = (0, add_swc_dependencies_1.addSwcDependencies)(tree);
13
+ tasks.push(addSwcTask);
14
+ }
15
+ if (options.compiler === 'tsc') {
16
+ devDependencies['tslib'] = versions_1.tsLibVersion;
17
+ }
18
+ if (options.uiFramework === 'react') {
19
+ devDependencies['@pmmmwh/react-refresh-webpack-plugin'] =
20
+ versions_1.reactRefreshWebpackPluginVersion;
21
+ devDependencies['@svgr/webpack'] = versions_1.svgrWebpackVersion;
22
+ devDependencies['react-refresh'] = versions_1.reactRefreshVersion;
23
+ }
24
+ tasks.push((0, devkit_1.addDependenciesToPackageJson)(tree, {}, devDependencies));
25
+ return (0, devkit_1.runTasksInSerial)(...tasks);
26
+ }
27
+ exports.ensureDependencies = ensureDependencies;
@@ -1,12 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getClientEnvironment = void 0;
4
+ // Prevent sensitive keys from being bundled when source code uses entire `process.env` object rather than individual keys (e.g. `process.env.NX_FOO`).
5
+ // TODO(v19): Only env vars prefixed with NX_PUBLIC should be bundled. This is a breaking change so we won't do it in v18.
6
+ const excludedKeys = ['NX_CLOUD_ACCESS_TOKEN', 'NX_CLOUD_ENCRYPTION_KEY'];
4
7
  function getClientEnvironment(mode) {
5
8
  // Grab NODE_ENV and NX_* environment variables and prepare them to be
6
9
  // injected into the application via DefinePlugin in webpack configuration.
7
10
  const NX_APP = /^NX_/i;
8
11
  const raw = Object.keys(process.env)
9
- .filter((key) => NX_APP.test(key))
12
+ .filter((key) => !excludedKeys.includes(key) && NX_APP.test(key))
10
13
  .reduce((env, key) => {
11
14
  env[key] = process.env[key];
12
15
  return env;
@@ -0,0 +1,2 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export declare function hasPlugin(tree: Tree): boolean;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasPlugin = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ function hasPlugin(tree) {
6
+ const nxJson = (0, devkit_1.readNxJson)(tree);
7
+ return !!nxJson.plugins?.some((p) => typeof p === 'string'
8
+ ? p === '@nx/webpack/plugin'
9
+ : p.plugin === '@nx/webpack/plugin');
10
+ }
11
+ exports.hasPlugin = hasPlugin;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getDependentPackagesForProject = void 0;
4
4
  const typescript_1 = require("./typescript");
5
+ const devkit_1 = require("@nx/devkit");
5
6
  function getDependentPackagesForProject(projectGraph, name) {
6
7
  const { npmPackages, workspaceLibraries } = collectDependencies(projectGraph, name);
7
8
  return {
@@ -34,11 +35,22 @@ function collectDependencies(projectGraph, name, dependencies = {
34
35
  return dependencies;
35
36
  }
36
37
  function getLibraryImportPath(library, projectGraph) {
38
+ let buildLibsFromSource = true;
39
+ if (process.env.NX_BUILD_LIBS_FROM_SOURCE) {
40
+ buildLibsFromSource = process.env.NX_BUILD_LIBS_FROM_SOURCE === 'true';
41
+ }
42
+ const libraryNode = projectGraph.nodes[library];
43
+ let sourceRoots = [libraryNode.data.sourceRoot];
44
+ if (!buildLibsFromSource && process.env.NX_BUILD_TARGET) {
45
+ const buildTarget = (0, devkit_1.parseTargetString)(process.env.NX_BUILD_TARGET, projectGraph);
46
+ sourceRoots = (0, devkit_1.getOutputsForTargetAndConfiguration)(buildTarget, {}, libraryNode);
47
+ }
37
48
  const tsConfigPathMappings = (0, typescript_1.readTsPathMappings)();
38
- const sourceRoot = projectGraph.nodes[library].data.sourceRoot;
39
49
  for (const [key, value] of Object.entries(tsConfigPathMappings)) {
40
- if (value.find((path) => path.startsWith(sourceRoot))) {
41
- return key;
50
+ for (const src of sourceRoots) {
51
+ if (value.find((path) => path.startsWith(src))) {
52
+ return key;
53
+ }
42
54
  }
43
55
  }
44
56
  return undefined;
@@ -7,7 +7,8 @@ interface ModuleFederationExecutorContext {
7
7
  }
8
8
  export declare function getRemotes(devRemotes: string[], skipRemotes: string[], config: ModuleFederationConfig, context: ModuleFederationExecutorContext, pathToManifestFile?: string): {
9
9
  staticRemotes: string[];
10
- devRemotes: string[];
10
+ devRemotes: any[];
11
+ dynamicRemotes: any[];
11
12
  remotePorts: any[];
12
13
  };
13
14
  export declare function getModuleFederationConfig(tsconfigPath: string, workspaceRoot: string, projectRoot: string, pluginName?: 'react' | 'angular'): any;
@@ -9,6 +9,7 @@ const path_1 = require("path");
9
9
  const fs_1 = require("fs");
10
10
  function extractRemoteProjectsFromConfig(config, pathToManifestFile) {
11
11
  const remotes = [];
12
+ const dynamicRemotes = [];
12
13
  if (pathToManifestFile && (0, fs_1.existsSync)(pathToManifestFile)) {
13
14
  const moduleFederationManifestJson = (0, fs_1.readFileSync)(pathToManifestFile, 'utf-8');
14
15
  if (moduleFederationManifestJson) {
@@ -18,13 +19,13 @@ function extractRemoteProjectsFromConfig(config, pathToManifestFile) {
18
19
  // }
19
20
  const parsedManifest = JSON.parse(moduleFederationManifestJson);
20
21
  if (Object.keys(parsedManifest).every((key) => typeof key === 'string' && typeof parsedManifest[key] === 'string')) {
21
- remotes.push(...Object.keys(parsedManifest));
22
+ dynamicRemotes.push(...Object.keys(parsedManifest));
22
23
  }
23
24
  }
24
25
  }
25
26
  const staticRemotes = config.remotes?.map((r) => (Array.isArray(r) ? r[0] : r)) ?? [];
26
27
  remotes.push(...staticRemotes);
27
- return remotes;
28
+ return { remotes, dynamicRemotes };
28
29
  }
29
30
  function collectRemoteProjects(remote, collected, context) {
30
31
  const remoteProject = context.projectGraph.nodes[remote]?.data;
@@ -35,30 +36,33 @@ function collectRemoteProjects(remote, collected, context) {
35
36
  const remoteProjectRoot = remoteProject.root;
36
37
  const remoteProjectTsConfig = remoteProject.targets['build'].options.tsConfig;
37
38
  const remoteProjectConfig = getModuleFederationConfig(remoteProjectTsConfig, context.root, remoteProjectRoot);
38
- const remoteProjectRemotes = extractRemoteProjectsFromConfig(remoteProjectConfig);
39
+ const { remotes: remoteProjectRemotes } = extractRemoteProjectsFromConfig(remoteProjectConfig);
39
40
  remoteProjectRemotes.forEach((r) => collectRemoteProjects(r, collected, context));
40
41
  }
41
42
  function getRemotes(devRemotes, skipRemotes, config, context, pathToManifestFile) {
42
43
  const collectedRemotes = new Set();
43
- const remotes = extractRemoteProjectsFromConfig(config, pathToManifestFile);
44
+ const { remotes, dynamicRemotes } = extractRemoteProjectsFromConfig(config, pathToManifestFile);
44
45
  remotes.forEach((r) => collectRemoteProjects(r, collectedRemotes, context));
45
46
  const remotesToSkip = new Set((0, find_matching_projects_1.findMatchingProjects)(skipRemotes, context.projectGraph.nodes) ?? []);
46
47
  if (remotesToSkip.size > 0) {
47
48
  devkit_1.logger.info(`Remotes not served automatically: ${[...remotesToSkip.values()].join(', ')}`);
48
49
  }
49
50
  const knownRemotes = Array.from(collectedRemotes).filter((r) => !remotesToSkip.has(r));
50
- devkit_1.logger.info(`NX Starting module federation dev-server for ${chalk.bold(context.projectName)} with ${knownRemotes.length} remotes`);
51
+ const knownDynamicRemotes = dynamicRemotes.filter((r) => !remotesToSkip.has(r));
52
+ devkit_1.logger.info(`NX Starting module federation dev-server for ${chalk.bold(context.projectName)} with ${[...knownRemotes, ...knownDynamicRemotes].length} remotes`);
51
53
  const devServeApps = new Set(!devRemotes
52
54
  ? []
53
55
  : Array.isArray(devRemotes)
54
56
  ? (0, find_matching_projects_1.findMatchingProjects)(devRemotes, context.projectGraph.nodes)
55
57
  : (0, find_matching_projects_1.findMatchingProjects)([devRemotes], context.projectGraph.nodes));
56
58
  const staticRemotes = knownRemotes.filter((r) => !devServeApps.has(r));
57
- const devServeRemotes = knownRemotes.filter((r) => devServeApps.has(r));
58
- const remotePorts = knownRemotes.map((r) => context.projectGraph.nodes[r].data.targets['serve'].options.port);
59
+ const devServeRemotes = [...knownRemotes, ...dynamicRemotes].filter((r) => devServeApps.has(r));
60
+ const staticDynamicRemotes = knownDynamicRemotes.filter((r) => !devServeApps.has(r));
61
+ const remotePorts = [...devServeRemotes, ...staticDynamicRemotes].map((r) => context.projectGraph.nodes[r].data.targets['serve'].options.port);
59
62
  return {
60
63
  staticRemotes,
61
64
  devRemotes: devServeRemotes,
65
+ dynamicRemotes: staticDynamicRemotes,
62
66
  remotePorts,
63
67
  };
64
68
  }
@@ -39,7 +39,7 @@ function handleArrayRemote(remote, remoteEntryExt, isRemoteGlobal) {
39
39
  : '';
40
40
  // if the remote is defined with anything other than http then we assume it's a promise based remote
41
41
  // In that case we should use what the user provides as the remote location
42
- if (remoteLocation.startsWith('http')) {
42
+ if (!remoteLocation.startsWith('promise new Promise')) {
43
43
  return `${globalPrefix}${baseRemote}/remoteEntry.${remoteEntryExt}`;
44
44
  }
45
45
  else {
@@ -6,7 +6,7 @@ const fs_1 = require("fs");
6
6
  const devkit_1 = require("@nx/devkit");
7
7
  const nx_1 = require("@nx/devkit/nx");
8
8
  let { readModulePackageJson } = (0, nx_1.requireNx)();
9
- // TODO: Remove this in Nx 18 when Nx 16.7.0 is no longer supported
9
+ // TODO: Remove this in Nx 19 when Nx 16.7.0 is no longer supported
10
10
  readModulePackageJson =
11
11
  readModulePackageJson ??
12
12
  require('nx/src/utils/package-json').readModulePackageJson;
@@ -4,18 +4,23 @@ exports.getRootTsConfigPath = exports.readTsConfig = exports.readTsPathMappings
4
4
  const fs_1 = require("fs");
5
5
  const path_1 = require("path");
6
6
  const devkit_1 = require("@nx/devkit");
7
- let tsConfig;
8
- let tsPathMappings;
7
+ let tsConfig = new Map();
8
+ let tsPathMappings = new Map();
9
9
  function readTsPathMappings(tsConfigPath = process.env.NX_TSCONFIG_PATH ?? getRootTsConfigPath()) {
10
- if (tsPathMappings) {
11
- return tsPathMappings;
10
+ if (tsPathMappings.has(tsConfigPath)) {
11
+ return tsPathMappings.get(tsConfigPath);
12
12
  }
13
- tsConfig ??= readTsConfiguration(tsConfigPath);
14
- tsPathMappings = {};
15
- Object.entries(tsConfig.options?.paths ?? {}).forEach(([alias, paths]) => {
16
- tsPathMappings[alias] = paths.map((path) => path.replace(/^\.\//, ''));
13
+ if (!tsConfig.has(tsConfigPath)) {
14
+ tsConfig.set(tsConfigPath, readTsConfiguration(tsConfigPath));
15
+ }
16
+ tsPathMappings.set(tsConfigPath, {});
17
+ Object.entries(tsConfig.get(tsConfigPath).options?.paths ?? {}).forEach(([alias, paths]) => {
18
+ tsPathMappings.set(tsConfigPath, {
19
+ ...tsPathMappings.get(tsConfigPath),
20
+ [alias]: paths.map((path) => path.replace(/^\.\//, '')),
21
+ });
17
22
  });
18
- return tsPathMappings;
23
+ return tsPathMappings.get(tsConfigPath);
19
24
  }
20
25
  exports.readTsPathMappings = readTsPathMappings;
21
26
  function readTsConfiguration(tsConfigPath) {
@@ -1,7 +1,7 @@
1
1
  export declare const nxVersion: any;
2
2
  export declare const swcLoaderVersion = "0.1.15";
3
3
  export declare const tsLibVersion = "^2.3.0";
4
+ export declare const webpackCliVersion = "^5.1.4";
4
5
  export declare const reactRefreshWebpackPluginVersion = "^0.5.7";
5
6
  export declare const svgrWebpackVersion = "^8.0.1";
6
7
  export declare const reactRefreshVersion = "^0.10.0";
7
- export declare const urlLoaderVersion = "^4.1.1";
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.urlLoaderVersion = exports.reactRefreshVersion = exports.svgrWebpackVersion = exports.reactRefreshWebpackPluginVersion = exports.tsLibVersion = exports.swcLoaderVersion = exports.nxVersion = void 0;
3
+ exports.reactRefreshVersion = exports.svgrWebpackVersion = exports.reactRefreshWebpackPluginVersion = exports.webpackCliVersion = exports.tsLibVersion = exports.swcLoaderVersion = exports.nxVersion = void 0;
4
4
  exports.nxVersion = require('../../package.json').version;
5
5
  exports.swcLoaderVersion = '0.1.15';
6
6
  exports.tsLibVersion = '^2.3.0';
7
+ exports.webpackCliVersion = '^5.1.4';
7
8
  // React apps
8
9
  exports.reactRefreshWebpackPluginVersion = '^0.5.7';
9
10
  exports.svgrWebpackVersion = '^8.0.1';
10
11
  exports.reactRefreshVersion = '^0.10.0';
11
- exports.urlLoaderVersion = '^4.1.1';
@@ -3,9 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const devkit_1 = require("@nx/devkit");
4
4
  // @ts-ignore
5
5
  const stylusLoader = require("stylus-loader");
6
- // TOOD(v18): Remove this file and stylus support.
6
+ // TOOD(v19): Remove this file and stylus support.
7
7
  function default_1(source) {
8
- devkit_1.logger.warn(`Stylus is support is deprecated and will be removed in Nx 18. We recommend that you migrate to Sass by renaming \`.styl\` files to \`.scss\` and ensuring that the content is valid Sass.`);
8
+ devkit_1.logger.warn(`Stylus is support is deprecated and will be removed in Nx 19. We recommend that you migrate to Sass by renaming \`.styl\` files to \`.scss\` and ensuring that the content is valid Sass.`);
9
9
  return stylusLoader.call(this, source);
10
10
  }
11
11
  exports.default = default_1;
@@ -7,8 +7,11 @@ function interpolateEnvironmentVariablesToIndex(contents, deployUrl) {
7
7
  }
8
8
  exports.interpolateEnvironmentVariablesToIndex = interpolateEnvironmentVariablesToIndex;
9
9
  const NX_PREFIX = /^NX_/i;
10
+ // Prevent sensitive keys from being bundled when source code uses entire `process.env` object rather than individual keys (e.g. `process.env.NX_FOO`).
11
+ // TODO(v19): Only env vars prefixed with NX_PUBLIC should be bundled. This is a breaking change so we won't do it in v18.
12
+ const excludedKeys = ['NX_CLOUD_ACCESS_TOKEN', 'NX_CLOUD_ENCRYPTION_KEY'];
10
13
  function isNxEnvironmentKey(x) {
11
- return NX_PREFIX.test(x);
14
+ return !excludedKeys.includes(x) && NX_PREFIX.test(x);
12
15
  }
13
16
  function getClientEnvironment(deployUrl) {
14
17
  return Object.keys(process.env)
@@ -122,7 +122,7 @@ function PostcssCliResources(options) {
122
122
  const resourceCache = new Map();
123
123
  return Promise.all(urlDeclarations.map(async (decl) => {
124
124
  const value = decl.value;
125
- const urlRegex = /url\(\s*(?:"([^"]+)"|'([^']+)'|(.+?))\s*\)/g;
125
+ const urlRegex = /url(?:\(\s*(['"]?))(.*?)(?:\1\s*\))/g;
126
126
  const segments = [];
127
127
  let match;
128
128
  let lastIndex = 0;
@@ -131,7 +131,7 @@ function PostcssCliResources(options) {
131
131
  const inputFile = decl.source && decl.source.input.file;
132
132
  const context = (inputFile && path.dirname(inputFile)) || loader.context;
133
133
  while ((match = urlRegex.exec(value))) {
134
- const originalUrl = match[1] || match[2] || match[3];
134
+ const originalUrl = match[2];
135
135
  let processedUrl;
136
136
  try {
137
137
  processedUrl = await process(originalUrl, context, resourceCache);
@@ -0,0 +1,10 @@
1
+ import { Configuration } from 'webpack';
2
+ /**
3
+ * Reads the webpack options from a give webpack configuration. The configuration can be:
4
+ * 1. A standard config object
5
+ * 2. A standard function that returns a config object (webpack.js.org/configuration/configuration-types/#exporting-a-function)
6
+ * 3. A Nx-specific composable function that takes Nx context, webpack config, and returns the config object.
7
+ *
8
+ * @param webpackConfig
9
+ */
10
+ export declare function readWebpackOptions(webpackConfig: unknown): Promise<Configuration>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readWebpackOptions = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const config_1 = require("../config");
6
+ /**
7
+ * Reads the webpack options from a give webpack configuration. The configuration can be:
8
+ * 1. A standard config object
9
+ * 2. A standard function that returns a config object (webpack.js.org/configuration/configuration-types/#exporting-a-function)
10
+ * 3. A Nx-specific composable function that takes Nx context, webpack config, and returns the config object.
11
+ *
12
+ * @param webpackConfig
13
+ */
14
+ async function readWebpackOptions(webpackConfig) {
15
+ let config;
16
+ if ((0, config_1.isNxWebpackComposablePlugin)(webpackConfig)) {
17
+ config = await webpackConfig({}, {
18
+ // These values are only used during build-time, so passing stubs here just to read out
19
+ // the returned config object.
20
+ options: {
21
+ root: devkit_1.workspaceRoot,
22
+ projectRoot: '',
23
+ sourceRoot: '',
24
+ outputFileName: undefined,
25
+ outputPath: undefined,
26
+ assets: undefined,
27
+ },
28
+ context: { root: devkit_1.workspaceRoot, cwd: undefined, isVerbose: false },
29
+ });
30
+ }
31
+ else if (typeof webpackConfig === 'function') {
32
+ config = await webpackConfig({
33
+ production: true, // we want the production build options
34
+ }, {});
35
+ }
36
+ else {
37
+ config = webpackConfig;
38
+ }
39
+ return config;
40
+ }
41
+ exports.readWebpackOptions = readWebpackOptions;
@@ -0,0 +1,3 @@
1
+ export declare function resolveUserDefinedWebpackConfig(path: string, tsConfig: string,
2
+ /** Skip require cache and return latest content */
3
+ reload?: boolean): any;
@@ -1,8 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isRegistered = exports.resolveCustomWebpackConfig = void 0;
3
+ exports.resolveUserDefinedWebpackConfig = void 0;
4
4
  const internal_1 = require("@nx/js/src/internal");
5
- function resolveCustomWebpackConfig(path, tsConfig) {
5
+ function resolveUserDefinedWebpackConfig(path, tsConfig,
6
+ /** Skip require cache and return latest content */
7
+ reload = false) {
8
+ if (reload) {
9
+ // Clear cache if the path is in the cache
10
+ if (require.cache[path]) {
11
+ // Clear all entries because config may import other modules
12
+ for (const k of Object.keys(require.cache)) {
13
+ delete require.cache[k];
14
+ }
15
+ }
16
+ }
6
17
  // Don't transpile non-TS files. This prevents workspaces libs from being registered via tsconfig-paths.
7
18
  // There's an issue here with Nx workspace where loading plugins from source (via tsconfig-paths) can lead to errors.
8
19
  if (!/\.(ts|mts|cts)$/.test(path)) {
@@ -25,9 +36,4 @@ function resolveCustomWebpackConfig(path, tsConfig) {
25
36
  : maybeCustomWebpackConfig;
26
37
  return customWebpackConfig;
27
38
  }
28
- exports.resolveCustomWebpackConfig = resolveCustomWebpackConfig;
29
- function isRegistered() {
30
- return (require.extensions['.ts'] != undefined ||
31
- require.extensions['.tsx'] != undefined);
32
- }
33
- exports.isRegistered = isRegistered;
39
+ exports.resolveUserDefinedWebpackConfig = resolveUserDefinedWebpackConfig;