-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
with-nx.ts
432 lines (386 loc) · 14.2 KB
/
with-nx.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
* WARNING: Do not add development dependencies to top-level imports.
* Instead, `require` them inline during the build phase.
*/
import type { NextConfig } from 'next';
import type { NextConfigFn } from '../src/utils/config';
import type { NextBuildBuilderOptions } from '../src/utils/types';
import {
type ExecutorContext,
type ProjectGraph,
type ProjectGraphProjectNode,
type Target,
} from '@nx/devkit';
export interface WithNxOptions extends NextConfig {
nx?: {
svgr?: boolean;
babelUpwardRootMode?: boolean;
};
}
export interface WithNxContext {
workspaceRoot: string;
libsDir: string;
}
function regexEqual(x, y) {
return (
x instanceof RegExp &&
y instanceof RegExp &&
x.source === y.source &&
x.global === y.global &&
x.ignoreCase === y.ignoreCase &&
x.multiline === y.multiline
);
}
/**
* Do not remove or rename this function. Production builds inline `with-nx.js` file with a replacement
* To this function that hard-codes the libsDir.
*/
function getWithNxContext(): WithNxContext {
const { workspaceRoot, workspaceLayout } = require('@nx/devkit');
return {
workspaceRoot,
libsDir: workspaceLayout().libsDir,
};
}
function getNxContext(
graph: ProjectGraph,
target: Target
): {
node: ProjectGraphProjectNode;
options: NextBuildBuilderOptions;
projectName: string;
targetName: string;
configurationName?: string;
} {
const { parseTargetString, workspaceRoot } = require('@nx/devkit');
const projectNode = graph.nodes[target.project];
const targetConfig = projectNode.data.targets[target.target];
const targetOptions = targetConfig.options;
if (target.configuration) {
Object.assign(
targetOptions,
targetConfig.configurations[target.configuration]
);
}
const partialExecutorContext: Partial<ExecutorContext> = {
projectName: target.project,
targetName: target.target,
projectGraph: graph,
configurationName: target.configuration,
root: workspaceRoot,
};
if (targetOptions.devServerTarget) {
// Executors such as @nx/cypress:cypress define the devServerTarget option.
return getNxContext(
graph,
parseTargetString(targetOptions.devServerTarget, partialExecutorContext)
);
} else if (targetOptions.buildTarget) {
// Executors such as @nx/next:server or @nx/next:export define the buildTarget option.
return getNxContext(
graph,
parseTargetString(targetOptions.buildTarget, partialExecutorContext)
);
}
// Default case, return info for current target.
// This could be a build using @nx/next:build or run-commands without using our executors.
return {
node: graph.nodes[target.project],
options: targetOptions,
projectName: target.project,
targetName: target.target,
configurationName: target.configuration,
};
}
/**
* Try to read output dir from project, and default to '.next' if executing outside of Nx (e.g. dist is added to a docker image).
*/
function withNx(
_nextConfig = {} as WithNxOptions,
context: WithNxContext = getWithNxContext()
): NextConfigFn {
return async (phase: string) => {
const { PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER } = await import(
'next/constants'
);
// Two scenarios where we want to skip graph creation:
// 1. Running production server means the build is already done so we just need to start the Next.js server.
// 2. During graph creation (i.e. create nodes), we won't have a graph to read, and it is not needed anyway since it's a build-time concern.
//
// NOTE: Avoid any `require(...)` or `import(...)` statements here. Development dependencies are not available at production runtime.
if (PHASE_PRODUCTION_SERVER === phase || global.NX_GRAPH_CREATION) {
const { nx, ...validNextConfig } = _nextConfig;
return {
distDir: '.next',
...validNextConfig,
};
} else {
const {
createProjectGraphAsync,
joinPathFragments,
offsetFromRoot,
workspaceRoot,
} = require('@nx/devkit');
let graph: ProjectGraph;
try {
graph = await createProjectGraphAsync();
} catch (e) {
throw new Error(
'Could not create project graph. Please ensure that your workspace is valid.',
{ cause: e }
);
}
const originalTarget = {
project: process.env.NX_TASK_TARGET_PROJECT,
target: process.env.NX_TASK_TARGET_TARGET,
configuration: process.env.NX_TASK_TARGET_CONFIGURATION,
};
const {
node: projectNode,
options,
projectName: project,
} = getNxContext(graph, originalTarget);
const projectDirectory = projectNode.data.root;
// Get next config
const nextConfig = getNextConfig(_nextConfig, context);
// For Next.js 13.1 and greater, make sure workspace libs are transpiled.
forNextVersion('>=13.1.0', () => {
if (!graph.dependencies[project]) return;
const { readTsConfigPaths } = require('@nx/js');
const {
findAllProjectNodeDependencies,
} = require('nx/src/utils/project-graph-utils');
const paths = readTsConfigPaths();
const deps = findAllProjectNodeDependencies(project);
nextConfig.transpilePackages ??= [];
for (const dep of deps) {
const alias = getAliasForProject(graph.nodes[dep], paths);
if (alias) {
nextConfig.transpilePackages.push(alias);
}
}
});
// process.env.NX_NEXT_OUTPUT_PATH is set when running @nx/next:build
options.outputPath =
process.env.NX_NEXT_OUTPUT_PATH || options.outputPath;
// outputPath may be undefined if using run-commands or other executors other than @nx/next:build.
// In this case, the user should set distDir in their next.config.js.
if (options.outputPath && phase !== PHASE_DEVELOPMENT_SERVER) {
const outputDir = `${offsetFromRoot(projectDirectory)}${
options.outputPath
}`;
// If running dev-server, we should keep `.next` inside project directory since Turbopack expects this.
// See: https://github.com/nrwl/nx/issues/19365
nextConfig.distDir =
nextConfig.distDir && nextConfig.distDir !== '.next'
? joinPathFragments(outputDir, nextConfig.distDir)
: joinPathFragments(outputDir, '.next');
}
// If we are running a static serve of the Next.js app, we need to change the output to 'export' and the distDir to 'out'.
if (process.env.NX_SERVE_STATIC_BUILD_RUNNING === 'true') {
nextConfig.output = 'export';
nextConfig.distDir = 'out';
}
const userWebpackConfig = nextConfig.webpack;
const { createWebpackConfig } = require('@nx/next/src/utils/config');
nextConfig.webpack = (a, b) =>
createWebpackConfig(
workspaceRoot,
projectDirectory,
options.fileReplacements,
options.assets
)(userWebpackConfig ? userWebpackConfig(a, b) : a, b);
return nextConfig;
}
};
}
export function getNextConfig(
nextConfig = {} as WithNxOptions,
context: WithNxContext = getWithNxContext()
): NextConfig {
// If `next-compose-plugins` is used, the context argument is invalid.
if (!context.libsDir || !context.workspaceRoot) {
context = getWithNxContext();
}
const userWebpack = nextConfig.webpack || ((x) => x);
const { nx, ...validNextConfig } = nextConfig;
return {
eslint: {
ignoreDuringBuilds: true,
...(validNextConfig.eslint ?? {}),
},
...validNextConfig,
webpack: (config, options) => {
/*
* Update babel to support our monorepo setup.
* The 'upward' mode allows the root babel.config.json and per-project .babelrc files to be picked up.
*/
if (nx?.babelUpwardRootMode) {
options.defaultLoaders.babel.options.babelrc = true;
options.defaultLoaders.babel.options.rootMode = 'upward';
}
/*
* Modify the Next.js webpack config to allow workspace libs to use css modules.
* Note: This would be easier if Next.js exposes css-loader and sass-loader on `defaultLoaders`.
*/
// Include workspace libs in css/sass loaders
const includes = [
require('path').join(context.workspaceRoot, context.libsDir),
];
const nextCssLoaders = config.module.rules.find(
(rule) => typeof rule.oneOf === 'object'
);
// webpack config is not as expected
if (!nextCssLoaders) return config;
/*
* 1. Modify css loader to enable module support for workspace libs
*/
const nextCssLoader = nextCssLoaders.oneOf.find(
(rule) =>
rule.sideEffects === false && regexEqual(rule.test, /\.module\.css$/)
);
// Might not be found if Next.js webpack config changes in the future
if (nextCssLoader && nextCssLoader.issuer) {
nextCssLoader.issuer.or = nextCssLoader.issuer.and
? nextCssLoader.issuer.and.concat(includes)
: includes;
delete nextCssLoader.issuer.and;
}
/*
* 2. Modify sass loader to enable module support for workspace libs
*/
const nextSassLoader = nextCssLoaders.oneOf.find(
(rule) =>
rule.sideEffects === false &&
regexEqual(rule.test, /\.module\.(scss|sass)$/)
);
// Might not be found if Next.js webpack config changes in the future
if (nextSassLoader && nextSassLoader.issuer) {
nextSassLoader.issuer.or = nextSassLoader.issuer.and
? nextSassLoader.issuer.and.concat(includes)
: includes;
delete nextSassLoader.issuer.and;
}
/*
* 3. Modify error loader to ignore css modules used by workspace libs
*/
const nextErrorCssModuleLoader = nextCssLoaders.oneOf.find(
(rule) =>
rule.use &&
rule.use.loader === 'error-loader' &&
rule.use.options &&
(rule.use.options.reason ===
'CSS Modules \u001b[1mcannot\u001b[22m be imported from within \u001b[1mnode_modules\u001b[22m.\n' +
'Read more: https://err.sh/next.js/css-modules-npm' ||
rule.use.options.reason ===
'CSS Modules cannot be imported from within node_modules.\nRead more: https://err.sh/next.js/css-modules-npm')
);
// Might not be found if Next.js webpack config changes in the future
if (nextErrorCssModuleLoader) {
nextErrorCssModuleLoader.exclude = includes;
}
/**
* 4. Modify css loader to allow global css from node_modules to be imported from workspace libs
*/
const nextGlobalCssLoader = nextCssLoaders.oneOf.find((rule) =>
rule.include?.and?.find((include) =>
regexEqual(include, /node_modules/)
)
);
// Might not be found if Next.js webpack config changes in the future
if (nextGlobalCssLoader && nextGlobalCssLoader.issuer) {
nextGlobalCssLoader.issuer.or = nextGlobalCssLoader.issuer.and
? nextGlobalCssLoader.issuer.and.concat(includes)
: includes;
delete nextGlobalCssLoader.issuer.and;
}
/**
* 5. Add env variables prefixed with NX_
*/
addNxEnvVariables(config);
/**
* 6. Add SVGR support if option is on.
*/
// Default SVGR support to be on for projects.
if (nx?.svgr !== false) {
config.module.rules.push(
// Apply rule for svg imports ending in ?url
{
test: /\.svg$/i,
type: 'asset',
resourceQuery: /url/, // apply to *.svg?url
},
// Convert all other svg imports to React components
{
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
resourceQuery: { not: [/url/] },
use: ['@svgr/webpack'],
}
);
}
return userWebpack(config, options);
},
};
}
// Prevent sensitive keys from being bundled when source code uses entire `process.env` object rather than individual keys (e.g. `process.env.NX_FOO`).
// TODO(v19): BREAKING: Only support NEXT_PUBLIC_ env vars and ignore NX_ vars since this is a standard Next.js feature.
const excludedKeys = ['NX_CLOUD_ACCESS_TOKEN', 'NX_CLOUD_ENCRYPTION_KEY'];
function getNxEnvironmentVariables() {
return Object.keys(process.env)
.filter((env) => !excludedKeys.includes(env) && /^NX_/i.test(env))
.reduce((env, key) => {
env[key] = process.env[key];
return env;
}, {});
}
/**
* TODO(v19)
* @deprecated Use Next.js 9.4+ built-in support for environment variables. Reference https://nextjs.org/docs/pages/api-reference/next-config-js/env
*/
function addNxEnvVariables(config: any) {
const maybeDefinePlugin = config.plugins?.find((plugin) => {
return plugin.definitions?.['process.env.NODE_ENV'];
});
if (maybeDefinePlugin) {
const env = getNxEnvironmentVariables();
Object.entries(env)
.map(([name, value]) => [`process.env.${name}`, `"${value}"`])
.filter(([name]) => !maybeDefinePlugin.definitions[name])
.forEach(
([name, value]) => (maybeDefinePlugin.definitions[name] = value)
);
}
}
export function getAliasForProject(
node: ProjectGraphProjectNode,
paths: Record<string, string[]>
): null | string {
// Match workspace libs to their alias in tsconfig paths.
for (const [alias, lookup] of Object.entries(paths ?? {})) {
const lookupContainsDepNode = lookup.some(
(lookupPath) =>
lookupPath.startsWith(node?.data?.root) ||
lookupPath.startsWith('./' + node?.data?.root)
);
if (lookupContainsDepNode) {
return alias;
}
}
return null;
}
// Runs a function if the Next.js version satisfies the range.
export function forNextVersion(range: string, fn: () => void) {
const semver = require('semver');
const nextJsVersion = require('next/package.json').version;
if (semver.satisfies(nextJsVersion, range)) {
fn();
}
}
// Support for older generated code: `const withNx = require('@nx/next/plugins/with-nx');`
module.exports = withNx;
// Support for newer generated code: `const { withNx } = require(...);`
module.exports.withNx = withNx;
module.exports.getNextConfig = getNextConfig;
module.exports.getAliasForProject = getAliasForProject;
export { withNx };