Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions e2e/next/src/next-legacy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import {
checkFilesExist,
cleanupProject,
detectPackageManager,
fileExists,
getPackageManagerCommand,
isNotWindows,
killPort,
listFiles,
newProject,
packageManagerLockFile,
readFile,
Expand Down Expand Up @@ -76,6 +78,8 @@ describe('@nx/next (legacy)', () => {
checkFilesExist(`dist/${appName}/redirects.js`);
checkFilesExist(`dist/${appName}/nested/headers.js`);
checkFilesExist(`dist/${appName}/nested/headers-2.js`);

checkBuildOutputIsSelfContained(`dist/${appName}`);
}, 120_000);

it('should build and install pruned lock file', async () => {
Expand Down Expand Up @@ -244,11 +248,7 @@ describe('@nx/next (legacy)', () => {
`dist/packages/${appName}/public/shared/ui/hello.txt`
);

// Check that compiled next config does not contain bad imports
const nextConfigPath = `dist/packages/${appName}/next.config.js`;
expect(nextConfigPath).not.toContain(`require("../`); // missing relative paths
expect(nextConfigPath).not.toContain(`require("nx/`); // dev-only packages
expect(nextConfigPath).not.toContain(`require("@nx/`); // dev-only packages
checkBuildOutputIsSelfContained(`dist/packages/${appName}`);

// Check that `nx serve <app> --prod` works with previous production build (e.g. `nx build <app>`).
const prodServePort = await reservePort();
Expand Down Expand Up @@ -320,3 +320,39 @@ describe('@nx/next (legacy)', () => {
);
}, 300_000);
});

// The build output must run where only the app's production dependencies are
// installed, so the rewritten next.config.js must not require dev-only packages
// and relative requires in the copied .nx-helpers files must resolve to files
// present in the output (nrwl/nx#36511).
function checkBuildOutputIsSelfContained(outputPath: string): void {
const nextConfigContent = readFile(`${outputPath}/next.config.js`);
for (const badImport of ['../', 'nx/', '@nx/']) {
expect(nextConfigContent).not.toContain(`require("${badImport}`);
expect(nextConfigContent).not.toContain(`require('${badImport}`);
}

const helpersDir = `${outputPath}/.nx-helpers`;
for (const helperFile of listFiles(helpersDir).filter((f) =>
f.endsWith('.js')
)) {
const content = readFile(`${helpersDir}/${helperFile}`);
for (const match of content.matchAll(
/require\((?:'(\.[^']+)'|"(\.[^"]+)")\)/g
)) {
const specifier = match[1] ?? match[2];
const resolves = [
specifier,
`${specifier}.js`,
`${specifier}/index.js`,
].some((candidate) =>
fileExists(tmpProjPath(join(helpersDir, candidate)))
);
if (!resolves) {
throw new Error(
`${helpersDir}/${helperFile} requires '${specifier}', which does not exist in the build output`
);
}
}
}
}
14 changes: 11 additions & 3 deletions packages/next/.oxlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
}
},
{
"files": ["plugins/with-nx.ts"],
"files": ["plugins/with-nx.ts", "src/utils/compose-plugins.ts"],
"rules": {
"no-restricted-imports": [
"error",
Expand All @@ -110,6 +110,14 @@
"name": "node-fetch",
"message": "Please default to native fetch instead of 'node-fetch'."
},
{
"name": "chalk",
"message": "Please use `picocolors` in place of `chalk` for rendering terminal colors"
},
{
"name": "fs-extra",
"message": "Please use native functionality in place of `fs-extra` for file-system interaction"
},
{
"name": "@nx/workspace"
},
Expand All @@ -130,7 +138,7 @@
"allowTypeImports": true
},
{
"group": ["./**/*"],
"group": [".", "..", "./**", "../**"],
"message": "Inline functions instead of importing relative files. Relative files are not available in dist.",
"allowTypeImports": true
},
Expand All @@ -140,7 +148,7 @@
"allowTypeImports": true
},
{
"group": ["nx/**/*"],
"group": ["nx", "nx/**/*"],
"message": "Do not import Nx package.",
"allowTypeImports": true
}
Expand Down
20 changes: 20 additions & 0 deletions packages/next/src/utils/compose-plugins.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,26 @@ describe('composePlugins', () => {
});
});

it('should not load the deprecation module, which is not copied into the .nx-helpers build output', async () => {
jest.resetModules();
jest.doMock('./deprecation', () => {
throw new Error('compose-plugins must not require ./deprecation');
});
try {
const {
composePlugins: isolatedComposePlugins,
} = require('./compose-plugins');
const { PHASE_PRODUCTION_SERVER } = require('next/constants');
const fn = await isolatedComposePlugins();
const output = await fn({ env: {} })(PHASE_PRODUCTION_SERVER, {});

expect(output).toEqual({ env: {} });
} finally {
jest.dontMock('./deprecation');
jest.resetModules();
}
});

it('should compose plugins that return an async function', async () => {
const nextConfig: NextConfig = {
env: {
Expand Down
21 changes: 19 additions & 2 deletions packages/next/src/utils/compose-plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type {
NextPlugin,
NextPluginThatReturnsConfigFn,
} from './config';
import { warnComposePluginsDeprecation } from './deprecation';

export function composePlugins(
...plugins: (NextPlugin | NextPluginThatReturnsConfigFn)[]
Expand All @@ -14,7 +13,25 @@ export function composePlugins(
phase: string,
context: any
): Promise<NextConfig> {
warnComposePluginsDeprecation(phase);
const {
PHASE_PRODUCTION_SERVER,
}: typeof import('next/constants') = require('next/constants');
// Copied verbatim into the build output (see create-next-config-file.ts),
// so this must load without @nx/next or @nx/devkit installed. Warn only on
// the active Nx-task path, resolved from the workspace like with-nx.ts.
if (
phase !== PHASE_PRODUCTION_SERVER &&
!global.NX_GRAPH_CREATION &&
process.env.NX_TASK_TARGET_TARGET
) {
const { workspaceRoot } = require('@nx/devkit');
const { warnComposePluginsDeprecation } = require(
require.resolve('@nx/next/src/utils/deprecation', {
paths: [workspaceRoot],
})
) as typeof import('./deprecation');
warnComposePluginsDeprecation(phase);
}
let config = baseConfig;
for (const plugin of plugins) {
const fn = await plugin;
Expand Down
Loading