Skip to content

Commit

Permalink
Merge branch 'master' into feat/disable-plugins-for-existing-workspaces
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenPandaz authored Feb 2, 2024
2 parents 974f8d7 + 9a9bd2a commit b596e09
Show file tree
Hide file tree
Showing 9 changed files with 131 additions and 61 deletions.
37 changes: 37 additions & 0 deletions e2e/webpack/src/webpack.legacy.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import {
checkFilesExist,
cleanupProject,
killProcessAndPorts,
newProject,
runCLI,
runCommandUntil,
uniq,
updateFile,
} from '@nx/e2e/utils';
import { ChildProcess } from 'child_process';

Expand Down Expand Up @@ -65,4 +67,39 @@ describe('Webpack Plugin (legacy)', () => {
await killProcessAndPorts(process.pid, port);
}
});

// Issue: https://github.com/nrwl/nx/issues/20179
it('should allow main/styles entries to be spread within composePlugins() function (#20179)', () => {
const appName = uniq('app');
runCLI(`generate @nx/web:app ${appName} --bundler webpack`);
updateFile(`apps/${appName}/src/main.ts`, `console.log('Hello');\n`);

updateFile(
`apps/${appName}/webpack.config.js`,
`
const { composePlugins, withNx, withWeb } = require('@nx/webpack');
module.exports = composePlugins(withNx(), withWeb(), (config) => {
return {
...config,
entry: {
main: [...config.entry.main],
styles: [...config.entry.styles],
}
};
});
`
);

expect(() => {
runCLI(`build ${appName} --outputHashing none`);
}).not.toThrow();
checkFilesExist(`dist/${appName}/styles.css`);

expect(() => {
runCLI(`build ${appName} --outputHashing none --extractCss false`);
}).not.toThrow();
expect(() => {
checkFilesExist(`dist/${appName}/styles.css`);
}).toThrow();
});
});
69 changes: 25 additions & 44 deletions e2e/webpack/src/webpack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ describe('Webpack Plugin', () => {
beforeAll(() => newProject());
afterAll(() => cleanupProject());

// TODO(crystal, @jaysoo): Investigate why this test is failing
xit('should be able to setup project to build node programs with webpack and different compilers', async () => {
it('should be able to setup project to build node programs with webpack and different compilers', async () => {
const myPkg = uniq('my-pkg');
runCLI(`generate @nx/js:lib ${myPkg} --bundler=none`);
updateFile(`libs/${myPkg}/src/index.ts`, `console.log('Hello');\n`);
Expand All @@ -29,13 +28,31 @@ describe('Webpack Plugin', () => {
updateFile(
`libs/${myPkg}/webpack.config.js`,
`
const { composePlugins, withNx } = require('@nx/webpack');
const path = require('path');
const { NxWebpackPlugin } = require('@nx/webpack');
class DebugPlugin {
apply(compiler) {
console.log('scriptType is ' + compiler.options.output.scriptType);
}
}
module.exports = composePlugins(withNx(), (config) => {
console.log('scriptType is ' + config.output.scriptType);
return config;
});
`
module.exports = {
target: 'node',
output: {
path: path.join(__dirname, '../../dist/libs/${myPkg}')
},
plugins: [
new NxWebpackPlugin({
compiler: 'tsc',
main: './src/index.ts',
tsConfig: './tsconfig.lib.json',
outputHashing: 'none',
optimization: false,
}),
new DebugPlugin()
]
};`
);

rmDist();
Expand Down Expand Up @@ -142,40 +159,4 @@ module.exports = composePlugins(withNx(), (config) => {
let output = runCommand(`node dist/${appName}/main.js`);
expect(output).toMatch(/Hello/);
}, 500_000);

// Issue: https://github.com/nrwl/nx/issues/20179
// TODO(crystal, @jaysoo): Investigate why this test is failing
xit('should allow main/styles entries to be spread within composePlugins() function (#20179)', () => {
const appName = uniq('app');
runCLI(`generate @nx/web:app ${appName} --bundler webpack`);
updateFile(`apps/${appName}/src/main.ts`, `console.log('Hello');\n`);

updateFile(
`apps/${appName}/webpack.config.js`,
`
const { composePlugins, withNx, withWeb } = require('@nx/webpack');
module.exports = composePlugins(withNx(), withWeb(), (config) => {
return {
...config,
entry: {
main: [...config.entry.main],
styles: [...config.entry.styles],
}
};
});
`
);

expect(() => {
runCLI(`build ${appName} --outputHashing none`);
}).not.toThrow();
checkFilesExist(`dist/apps/${appName}/styles.css`);

expect(() => {
runCLI(`build ${appName} --outputHashing none --extractCss false`);
}).not.toThrow();
expect(() => {
checkFilesExist(`dist/apps/${appName}/styles.css`);
}).toThrow();
});
});
10 changes: 10 additions & 0 deletions packages/nx/src/executors/run-script/run-script.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,17 @@ export default async function (
context.root,
context.projectsConfigurations.projects[context.projectName].root
);

let env = process.env;
// when running nx through npx with node_modules installed with npm, the path gets modified to include the full workspace path with the node_modules folder
// This causes issues when running in a pty process, so we filter out the node_modules paths from the PATH
// Since the command here will be run with the package manager script command, the path will be modified again within the PTY process itself.
let filteredPath =
env.PATH?.split(path.delimiter)
.filter((p) => !p.startsWith(path.join(context.root, 'node_modules')))
.join(path.delimiter) ?? '';
env.PATH = filteredPath;

if (process.stdout.isTTY) {
await ptyProcess(command, cwd, env);
} else {
Expand Down
14 changes: 7 additions & 7 deletions packages/rollup/src/executors/rollup/rollup.impl.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ describe('rollupExecutor', () => {
),
[],
context,
{ name: 'example' },
{ name: 'example', version: '1.0' },
'/root/src',
[]
);
Expand Down Expand Up @@ -81,7 +81,7 @@ describe('rollupExecutor', () => {
),
[],
context,
{ name: 'example' },
{ name: 'example', version: '1.0' },
'/root/src',
[]
);
Expand Down Expand Up @@ -117,7 +117,7 @@ describe('rollupExecutor', () => {
),
[],
context,
{ name: 'example' },
{ name: 'example', version: '1.0' },
'/root/src',
[]
);
Expand Down Expand Up @@ -146,7 +146,7 @@ describe('rollupExecutor', () => {
},
[],
context,
{ name: 'example' },
{ name: 'example', version: '1.0' },
'/root/src',
[]
);
Expand All @@ -165,7 +165,7 @@ describe('rollupExecutor', () => {
),
[],
context,
{ name: 'example' },
{ name: 'example', version: '1.0' },
'/root/src',
['lodash']
);
Expand All @@ -186,7 +186,7 @@ describe('rollupExecutor', () => {
),
[],
context,
{ name: 'example' },
{ name: 'example', version: '1.0' },
'/root/src',
['lodash']
);
Expand All @@ -207,7 +207,7 @@ describe('rollupExecutor', () => {
),
[],
context,
{ name: 'example' },
{ name: 'example', version: '1.0' },
'/root/src',
['lodash']
);
Expand Down
21 changes: 19 additions & 2 deletions packages/rollup/src/executors/rollup/rollup.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
DependentBuildableProjectNode,
} from '@nx/js/src/utils/buildable-libs-utils';
import nodeResolve from '@rollup/plugin-node-resolve';
import type { PackageJson } from 'nx/src/utils/package-json';
import { typeDefinitions } from '@nx/js/src/plugins/rollup/type-definitions';

import { AssetGlobPattern, RollupExecutorOptions } from './schema';
import { runRollup } from './lib/run-rollup';
Expand All @@ -26,7 +28,6 @@ import { analyze } from './lib/analyze-plugin';
import { deleteOutputDir } from '../../utils/fs';
import { swc } from './lib/swc-plugin';
import { updatePackageJson } from './lib/update-package-json';
import { typeDefinitions } from '@nx/js/src/plugins/rollup/type-definitions';

export type RollupExecutorEvent = {
success: boolean;
Expand Down Expand Up @@ -158,7 +159,7 @@ export function createRollupOptions(
options: NormalizedRollupExecutorOptions,
dependencies: DependentBuildableProjectNode[],
context: ExecutorContext,
packageJson: any,
packageJson: PackageJson,
sourceRoot: string,
npmDeps: string[]
): rollup.InputOptions[] {
Expand All @@ -178,6 +179,22 @@ export function createRollupOptions(
options.format = readCompatibleFormats(config);
}

if (packageJson.type === 'module') {
if (options.format.includes('cjs')) {
logger.warn(
`Package type is set to "module" but "cjs" format is included. Going to use "esm" format instead. You can change the package type to "commonjs" or remove type in the package.json file.`
);
}
options.format = ['esm'];
} else if (packageJson.type === 'commonjs') {
if (options.format.includes('esm')) {
logger.warn(
`Package type is set to "commonjs" but "esm" format is included. Going to use "cjs" format instead. You can change the package type to "module" or remove type in the package.json file.`
);
}
options.format = ['cjs'];
}

return options.format.map((format, idx) => {
// Either we're generating only one format, so we should bundle types
// OR we are generating dual formats, so only bundle types for CJS.
Expand Down
12 changes: 9 additions & 3 deletions packages/vite/plugins/nx-tsconfig-paths.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { stripIndents, workspaceRoot } from '@nx/devkit';
import { joinPathFragments, stripIndents, workspaceRoot } from '@nx/devkit';
import { existsSync } from 'node:fs';
import { relative, join, resolve } from 'node:path';
import {
Expand Down Expand Up @@ -153,8 +153,14 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th
const normalizedImport = alias.replace(/\/\*$/, '');

if (importPath.startsWith(normalizedImport)) {
const path = (tsconfig.absoluteBaseUrl, paths[0].replace(/\/\*$/, ''));
resolvedFile = findFile(importPath.replace(normalizedImport, path));
const joinedPath = joinPathFragments(
tsconfig.absoluteBaseUrl,
paths[0].replace(/\/\*$/, '')
);

resolvedFile = findFile(
importPath.replace(normalizedImport, joinedPath)
);
}
}

Expand Down
26 changes: 22 additions & 4 deletions packages/webpack/src/generators/configuration/configuration.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import {
formatFiles,
GeneratorCallback,
joinPathFragments,
offsetFromRoot,
readProjectConfiguration,
runTasksInSerial,
Tree,
updateProjectConfiguration,
writeJson,
Expand All @@ -12,6 +15,7 @@ import { ConfigurationGeneratorSchema } from './schema';
import { WebpackExecutorOptions } from '../../executors/webpack/schema';
import { hasPlugin } from '../../utils/has-plugin';
import { addBuildTargetDefaults } from '@nx/devkit/src/generators/add-build-target-defaults';
import { ensureDependencies } from '../../utils/ensure-dependencies';

export function configurationGenerator(
tree: Tree,
Expand All @@ -24,12 +28,20 @@ export async function configurationGeneratorInternal(
tree: Tree,
options: ConfigurationGeneratorSchema
) {
const tasks: GeneratorCallback[] = [];
options.addPlugin ??= process.env.NX_ADD_PLUGINS !== 'false';

const task = await webpackInitGenerator(tree, {
const initTask = await webpackInitGenerator(tree, {
...options,
skipFormat: true,
});
tasks.push(initTask);

const depsTask = ensureDependencies(tree, {
compiler: options.compiler === 'babel' ? undefined : options.compiler,
});
tasks.push(depsTask);

checkForTargetConflicts(tree, options);

if (!hasPlugin(tree)) {
Expand All @@ -45,7 +57,7 @@ export async function configurationGeneratorInternal(
await formatFiles(tree);
}

return task;
return runTasksInSerial(...tasks);
}

function checkForTargetConflicts(
Expand Down Expand Up @@ -94,14 +106,17 @@ const { join } = require('path');
module.exports = {
output: {
path: join(__dirname, '${buildOptions.outputPath}'),
path: join(__dirname, '${offsetFromRoot(project.root)}${
buildOptions.outputPath
}'),
},
plugins: [
new NxWebpackPlugin({
target: '${buildOptions.target}',
tsConfig: '${buildOptions.tsConfig}',
compiler: '${buildOptions.compiler}',
main: '${buildOptions.main}',
outputHashing: '${buildOptions.target !== 'web' ? 'none' : 'all'}',
})
],
}
Expand All @@ -127,14 +142,17 @@ const { join } = require('path');
module.exports = {
output: {
path: join(__dirname, '${buildOptions.outputPath}'),
path: join(__dirname, '${offsetFromRoot(project.root)}${
buildOptions.outputPath
}'),
},
plugins: [
new NxWebpackPlugin({
target: '${buildOptions.target}',
tsConfig: '${buildOptions.tsConfig}',
compiler: '${buildOptions.compiler}',
main: '${buildOptions.main}',
outputHashing: '${buildOptions.target !== 'web' ? 'none' : 'all'}',
})
],
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export function normalizeOptions(
sourceMap: options.sourceMap ?? !isProd,
sourceRoot,
styles: options.styles ?? [],
target: options.target ?? 'web',
target: options.target,
targetName,
vendorChunk: options.vendorChunk ?? !isProd,
};
Expand Down
1 change: 1 addition & 0 deletions packages/webpack/src/utils/with-nx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export function withNx(
{
...options,
...pluginOptions,
target: options.target ?? 'web',
assets: options.assets
? options.assets
: pluginOptions.assets
Expand Down

0 comments on commit b596e09

Please sign in to comment.