Skip to content

Commit

Permalink
feat(rollup): use .cjs file extension for config files (#29196)
Browse files Browse the repository at this point in the history
The `rollup.config.js` file will be resolved as ESM if the closest
`package.json` has `type: 'module`. This causes an error when computing
the project graph and when reading the file for builds.

```
  Original error: require is not defined in ES module scope, you can use import instead
```

<!-- If this is a particularly complex change or feature addition, you
can request a dedicated Nx release for this pull request branch. Mention
someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they
will confirm if the PR warrants its own release for testing purposes,
and generate it for you if appropriate. -->

This PR also updates the output directory to `{projectRoot}/dist` for
the new TS setup.

## Current Behavior
`nx g @nx/react:lib --bundler=rollup` has an error due to Node
resolution

## Expected Behavior
`nx g @nx/react:lib --bundler=rollup` works out of the box

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #29193, #[29195](#29195)

---------

Co-authored-by: Leosvel Pérez Espinosa <[email protected]>
  • Loading branch information
jaysoo and leosvelperez authored Dec 4, 2024
1 parent 972c01b commit 6c5916a
Show file tree
Hide file tree
Showing 15 changed files with 291 additions and 90 deletions.
2 changes: 1 addition & 1 deletion e2e/react/src/react-package.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ describe('Build React libraries and apps', () => {

// Add assets to child lib
updateFile(
join('libs', childLib, 'rollup.config.js'),
join('libs', childLib, 'rollup.config.cjs'),
`const { withNx } = require('@nx/rollup/with-nx');
module.exports = withNx(
{
Expand Down
10 changes: 5 additions & 5 deletions e2e/rollup/src/rollup-legacy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,13 +185,13 @@ describe('Rollup Plugin', () => {
checkFilesExist(`dist/test/index.mjs.js`);
});

it('should support array config from rollup.config.js', () => {
it('should support array config from rollup.config.cjs', () => {
const jsLib = uniq('jslib');
runCLI(
`generate @nx/js:lib ${jsLib} --directory=libs/${jsLib} --bundler rollup --verbose`
);
updateFile(
`libs/${jsLib}/rollup.config.js`,
`libs/${jsLib}/rollup.config.cjs`,
`module.exports = (config) => [{
...config,
output: {
Expand All @@ -204,7 +204,7 @@ describe('Rollup Plugin', () => {
}]`
);
updateJson(join('libs', jsLib, 'project.json'), (config) => {
config.targets.build.options.rollupConfig = `libs/${jsLib}/rollup.config.js`;
config.targets.build.options.rollupConfig = `libs/${jsLib}/rollup.config.cjs`;
return config;
});

Expand All @@ -219,15 +219,15 @@ describe('Rollup Plugin', () => {
`generate @nx/js:lib ${jsLib} --directory=libs/${jsLib} --bundler rollup --verbose`
);
updateFile(
`libs/${jsLib}/rollup.config.js`,
`libs/${jsLib}/rollup.config.cjs`,
`module.exports = (config) => ({
...config,
// Filter out the plugin, but the @nx/rollup:rollup executor should add it back
plugins: config.plugins.filter((p) => p.name !== 'rollup-plugin-nx-generate-package-json'),
})`
);
updateJson(join('libs', jsLib, 'project.json'), (config) => {
config.targets.build.options.rollupConfig = `libs/${jsLib}/rollup.config.js`;
config.targets.build.options.rollupConfig = `libs/${jsLib}/rollup.config.cjs`;
return config;
});

Expand Down
8 changes: 4 additions & 4 deletions e2e/rollup/src/rollup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('Rollup Plugin', () => {
`generate @nx/rollup:configuration ${myPkg} --tsConfig=./tsconfig.lib.json --main=./src/index.ts`
);
updateFile(
`libs/${myPkg}/rollup.config.js`,
`libs/${myPkg}/rollup.config.cjs`,
`
const { withNx } = require('@nx/rollup/with-nx');
module.exports = withNx({
Expand Down Expand Up @@ -61,7 +61,7 @@ describe('Rollup Plugin', () => {
`generate @nx/rollup:configuration ${myPkg} --tsConfig=./tsconfig.lib.json --main=./src/index.ts --compiler=swc`
);
updateFile(
`libs/${myPkg}/rollup.config.js`,
`libs/${myPkg}/rollup.config.cjs`,
`
const { withNx } = require('@nx/rollup/with-nx');
module.exports = withNx({
Expand All @@ -85,7 +85,7 @@ describe('Rollup Plugin', () => {
`generate @nx/rollup:configuration ${myPkg} --tsConfig=./tsconfig.lib.json --main=./src/index.ts --compiler=tsc`
);
updateFile(
`libs/${myPkg}/rollup.config.js`,
`libs/${myPkg}/rollup.config.cjs`,
`
const { withNx } = require('@nx/rollup/with-nx');
module.exports = withNx({
Expand Down Expand Up @@ -114,7 +114,7 @@ describe('Rollup Plugin', () => {
`generate @nx/rollup:configuration ${myPkg} --tsConfig=./tsconfig.lib.json --main=./src/index.ts --compiler=tsc`
);
updateFile(
`libs/${myPkg}/rollup.config.js`,
`libs/${myPkg}/rollup.config.cjs`,
`
const { withNx } = require('@nx/rollup/with-nx');
module.exports = withNx({
Expand Down
2 changes: 1 addition & 1 deletion packages/js/src/generators/setup-build/generator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ describe('setup-build generator', () => {
bundler: 'rollup',
});

expect(tree.exists('packages/mypkg/rollup.config.js')).toBe(true);
expect(tree.exists('packages/mypkg/rollup.config.cjs')).toBe(true);
});

it('should support --bundler=esbuild', async () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/react/plugins/bundle-rollup.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as rollup from 'rollup';

// TODO(v22): Remove this in Nx 22 and migrate to explicit rollup.config.js files.
// TODO(v22): Remove this in Nx 22 and migrate to explicit rollup.config.cjs files.
/**
* @deprecated Use `withNx` function from `@nx/rollup/with-nx` in your rollup.config.js file instead. Use `nx g @nx/rollup:convert-to-inferred` to generate the rollup.config.js file if it does not exist.
* @deprecated Use `withNx` function from `@nx/rollup/with-nx` in your rollup.config.cjs file instead. Use `nx g @nx/rollup:convert-to-inferred` to generate the rollup.config.cjs file if it does not exist.
*/
function getRollupOptions(options: rollup.RollupOptions) {
const extraGlobals = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
readNxJson,
readProjectConfiguration,
runTasksInSerial,
stripIndents,
updateProjectConfiguration,
} from '@nx/devkit';

Expand Down Expand Up @@ -69,38 +68,43 @@ export async function addRollupBuildTarget(
if (hasRollupPlugin) {
// New behavior, using rollup config file and inferred target.
host.write(
joinPathFragments(options.projectRoot, 'rollup.config.js'),
stripIndents`
const { withNx } = require('@nx/rollup/with-nx');
const url = require('@rollup/plugin-url');
const svg = require('@svgr/rollup');
module.exports = withNx({
main: '${maybeJs(options, './src/index.ts')}',
outputPath: '${joinPathFragments(
offsetFromRoot(options.projectRoot),
'dist',
options.projectRoot
)}',
tsConfig: './tsconfig.lib.json',
compiler: '${options.compiler ?? 'babel'}',
external: ${JSON.stringify(external)},
format: ['esm'],
assets:[{ input: '.', output: '.', glob: 'README.md'}],
}, {
// Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
plugins: [
svg({
svgo: false,
titleProp: true,
ref: true,
}),
url({
limit: 10000, // 10kB
}),
],
});
`
joinPathFragments(options.projectRoot, 'rollup.config.cjs'),
`const { withNx } = require('@nx/rollup/with-nx');
const url = require('@rollup/plugin-url');
const svg = require('@svgr/rollup');
module.exports = withNx(
{
main: '${maybeJs(options, './src/index.ts')}',
outputPath: '${
options.isUsingTsSolutionConfig
? './dist'
: joinPathFragments(
offsetFromRoot(options.projectRoot),
'dist',
options.projectRoot
)
}',
tsConfig: './tsconfig.lib.json',
compiler: '${options.compiler ?? 'babel'}',
external: ${JSON.stringify(external)},
format: ['esm'],
assets:[{ input: '.', output: '.', glob: 'README.md'}],
}, {
// Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
plugins: [
svg({
svgo: false,
titleProp: true,
ref: true,
}),
url({
limit: 10000, // 10kB
}),
],
}
);
`
);
} else {
// Legacy behavior, there is a target in project.json using rollup executor.
Expand Down
129 changes: 127 additions & 2 deletions packages/react/src/generators/library/library.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,37 @@ describe('lib', () => {
buildable: true,
});

expect(tree.exists('my-lib/rollup.config.js')).toBeTruthy();
expect(tree.read('my-lib/rollup.config.cjs', 'utf-8'))
.toMatchInlineSnapshot(`
"const { withNx } = require('@nx/rollup/with-nx');
const url = require('@rollup/plugin-url');
const svg = require('@svgr/rollup');
module.exports = withNx(
{
main: './src/index.ts',
outputPath: '../dist/my-lib',
tsConfig: './tsconfig.lib.json',
compiler: 'babel',
external: ["react","react-dom","react/jsx-runtime"],
format: ['esm'],
assets:[{ input: '.', output: '.', glob: 'README.md'}],
}, {
// Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
plugins: [
svg({
svgo: false,
titleProp: true,
ref: true,
}),
url({
limit: 10000, // 10kB
}),
],
}
);
"
`);
});
});

Expand Down Expand Up @@ -558,7 +588,7 @@ describe('lib', () => {
importPath: '@proj/my-lib',
});

expect(tree.read('my-lib/rollup.config.js', 'utf-8'))
expect(tree.read('my-lib/rollup.config.cjs', 'utf-8'))
.toEqual(`const { withNx } = require('@nx/rollup/with-nx');
const url = require('@rollup/plugin-url');
const svg = require('@svgr/rollup');
Expand Down Expand Up @@ -906,6 +936,59 @@ module.exports = withNx(
name: 'mylib',
});

expect(tree.read('mylib/vite.config.ts', 'utf-8')).toMatchInlineSnapshot(`
"/// <reference types='vitest' />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import dts from 'vite-plugin-dts';
import * as path from 'path';
export default defineConfig({
root: __dirname,
cacheDir: '../node_modules/.vite/mylib',
plugins: [react(), dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.lib.json') })],
// Uncomment this if you are using workers.
// worker: {
// plugins: [ nxViteTsPaths() ],
// },
// Configuration for building your library.
// See: https://vitejs.dev/guide/build.html#library-mode
build: {
outDir: './dist',
emptyOutDir: true,
reportCompressedSize: true,
commonjsOptions: {
transformMixedEsModules: true,
},
lib: {
// Could also be a dictionary or array of multiple entry points.
entry: 'src/index.ts',
name: 'mylib',
fileName: 'index',
// Change this to the formats you want to support.
// Don't forget to update your package.json as well.
formats: ['es', 'cjs']
},
rollupOptions: {
// External packages that should not be bundled into your library.
external: ['react','react-dom','react/jsx-runtime']
},
},
test: {
watch: false,
globals: true,
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['default'],
coverage: {
reportsDirectory: '../coverage/mylib',
provider: 'v8',
}
},
});
"
`);

expect(readJson(tree, 'tsconfig.json').references).toMatchInlineSnapshot(`
[
{
Expand Down Expand Up @@ -1061,5 +1144,47 @@ module.exports = withNx(
}
`);
});

it('should configure rollup correctly', async () => {
await libraryGenerator(tree, {
...defaultSchema,
bundler: 'rollup',
unitTestRunner: 'none',
directory: 'mylib',
name: 'mylib',
});

expect(tree.read('mylib/rollup.config.cjs', 'utf-8'))
.toMatchInlineSnapshot(`
"const { withNx } = require('@nx/rollup/with-nx');
const url = require('@rollup/plugin-url');
const svg = require('@svgr/rollup');
module.exports = withNx(
{
main: './src/index.ts',
outputPath: './dist',
tsConfig: './tsconfig.lib.json',
compiler: 'babel',
external: ["react","react-dom","react/jsx-runtime"],
format: ['esm'],
assets:[{ input: '.', output: '.', glob: 'README.md'}],
}, {
// Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
plugins: [
svg({
svgo: false,
titleProp: true,
ref: true,
}),
url({
limit: 10000, // 10kB
}),
],
}
);
"
`);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe('configurationGenerator', () => {
main: './libs/mypkg/src/index.ts',
});

const rollupConfig = tree.read('libs/mypkg/rollup.config.js', 'utf-8');
const rollupConfig = tree.read('libs/mypkg/rollup.config.cjs', 'utf-8');

expect(rollupConfig)
.toEqual(`const { withNx } = require('@nx/rollup/with-nx');
Expand Down Expand Up @@ -88,7 +88,7 @@ module.exports = withNx(
tsConfig: 'libs/mypkg/tsconfig.custom.json',
});

const rollupConfig = tree.read('libs/mypkg/rollup.config.js', 'utf-8');
const rollupConfig = tree.read('libs/mypkg/rollup.config.cjs', 'utf-8');

expect(rollupConfig)
.toEqual(`const { withNx } = require('@nx/rollup/with-nx');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ function createRollupConfig(
};

tree.write(
joinPathFragments(project.root, 'rollup.config.js'),
joinPathFragments(project.root, 'rollup.config.cjs'),
`const { withNx } = require('@nx/rollup/with-nx');
module.exports = withNx(
Expand Down
Loading

0 comments on commit 6c5916a

Please sign in to comment.