@nx/rollup 17.0.2 → 17.0.4

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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  (The MIT License)
2
2
 
3
- Copyright (c) 2017-2023 Narwhal Technologies Inc.
3
+ Copyright (c) 2017-2024 Narwhal Technologies Inc.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining
6
6
  a copy of this software and associated documentation files (the
package/README.md CHANGED
@@ -1,4 +1,9 @@
1
- <p style="text-align: center;"><img src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx.png" width="600" alt="Nx - Smart, Fast and Extensible Build System"></p>
1
+ <p style="text-align: center;">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-dark.svg">
4
+ <img alt="Nx - Smart Monorepos · Fast CI" src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-light.svg" width="100%">
5
+ </picture>
6
+ </p>
2
7
 
3
8
  <div style="text-align: center;">
4
9
 
@@ -15,9 +20,9 @@
15
20
 
16
21
  <hr>
17
22
 
18
- # Nx: Smart, Fast and Extensible Build System
23
+ # Nx: Smart Monorepos · Fast CI
19
24
 
20
- Nx is a next generation build system with first class monorepo support and powerful integrations.
25
+ Nx is a build system with built-in tooling and advanced CI capabilities. It helps you maintain and scale monorepos, both locally and on CI.
21
26
 
22
27
  This package is a [Rollup plugin for Nx](https://nx.dev/packages/rollup).
23
28
 
@@ -59,5 +64,5 @@ npx nx@latest init
59
64
  - [Blog Posts About Nx](https://blog.nrwl.io/nx/home)
60
65
 
61
66
  <p style="text-align: center;"><a href="https://nx.dev/#learning-materials" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-courses-and-videos.svg"
62
- width="100%" alt="Nx - Smart, Fast and Extensible Build System"></a></p>
67
+ width="100%" alt="Nx - Smart Monorepos · Fast CI"></a></p>
63
68
 
package/migrations.json CHANGED
@@ -25,5 +25,15 @@
25
25
  "factory": "./src/migrations/update-16-6-0/explicitly-set-projects-to-update-buildable-deps"
26
26
  }
27
27
  },
28
- "packageJsonUpdates": {}
28
+ "packageJsonUpdates": {
29
+ "18.2.0": {
30
+ "version": "18.2.0-beta.1",
31
+ "packages": {
32
+ "core-js": {
33
+ "version": "3.36.1",
34
+ "alwaysAddToPackageJson": false
35
+ }
36
+ }
37
+ }
38
+ }
29
39
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/rollup",
3
- "version": "17.0.2",
3
+ "version": "17.0.4",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for Rollup contains executors and generators that support building applications using Rollup.",
6
6
  "repository": {
@@ -37,18 +37,16 @@
37
37
  "autoprefixer": "^10.4.9",
38
38
  "babel-plugin-transform-async-to-promises": "^0.8.15",
39
39
  "chalk": "^4.1.0",
40
- "fast-glob": "^3.2.7",
41
40
  "postcss": "^8.4.14",
42
41
  "rollup": "^2.56.2",
43
42
  "rollup-plugin-copy": "^3.4.0",
44
43
  "rollup-plugin-peer-deps-external": "^2.2.4",
45
44
  "rollup-plugin-postcss": "^4.0.1",
46
- "rollup-plugin-typescript2": "0.34.1",
47
- "rxjs": "^7.8.0",
45
+ "rollup-plugin-typescript2": "0.36.0",
48
46
  "tslib": "^2.3.0",
49
- "@nx/devkit": "17.0.2",
50
- "@nx/js": "17.0.2",
51
- "@nrwl/rollup": "17.0.2"
47
+ "@nx/devkit": "17.0.4",
48
+ "@nx/js": "17.0.4",
49
+ "@nrwl/rollup": "17.0.4"
52
50
  },
53
51
  "publishConfig": {
54
52
  "access": "public"
package/plugin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { createNodes, RollupPluginOptions } from './src/plugins/plugin';
package/plugin.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNodes = void 0;
4
+ var plugin_1 = require("./src/plugins/plugin");
5
+ Object.defineProperty(exports, "createNodes", { enumerable: true, get: function () { return plugin_1.createNodes; } });
@@ -21,7 +21,8 @@ function updatePackageJson(options, packageJson) {
21
21
  });
22
22
  packageJson.module = esmExports['.'];
23
23
  if (!hasCjsFormat) {
24
- packageJson.type = 'module';
24
+ if (!options.skipTypeField)
25
+ packageJson.type = 'module';
25
26
  packageJson.main ??= esmExports['.'];
26
27
  }
27
28
  if (options.generateExportsField) {
@@ -1,12 +1,15 @@
1
1
  import * as rollup from 'rollup';
2
- import type { ExecutorContext } from '@nx/devkit';
2
+ import { type ExecutorContext } from '@nx/devkit';
3
3
  import { DependentBuildableProjectNode } from '@nx/js/src/utils/buildable-libs-utils';
4
+ import type { PackageJson } from 'nx/src/utils/package-json';
4
5
  import { RollupExecutorOptions } from './schema';
5
6
  import { NormalizedRollupExecutorOptions } from './lib/normalize';
6
- export type RollupExecutorEvent = {
7
+ export declare function rollupExecutor(rawOptions: RollupExecutorOptions, context: ExecutorContext): AsyncGenerator<never, AsyncIterable<unknown> | {
7
8
  success: boolean;
8
- outfile?: string;
9
- };
10
- export declare function rollupExecutor(rawOptions: RollupExecutorOptions, context: ExecutorContext): AsyncGenerator<RollupExecutorEvent, any, undefined>;
11
- export declare function createRollupOptions(options: NormalizedRollupExecutorOptions, dependencies: DependentBuildableProjectNode[], context: ExecutorContext, packageJson: any, sourceRoot: string, npmDeps: string[]): rollup.InputOptions[];
9
+ outfile: string;
10
+ } | {
11
+ success: boolean;
12
+ outfile?: undefined;
13
+ }, unknown>;
14
+ export declare function createRollupOptions(options: NormalizedRollupExecutorOptions, dependencies: DependentBuildableProjectNode[], context: ExecutorContext, packageJson: PackageJson, sourceRoot: string, npmDeps: string[]): Promise<rollup.RollupOptions>;
12
15
  export default rollupExecutor;
@@ -6,20 +6,18 @@ const rollup = require("rollup");
6
6
  const peerDepsExternal = require("rollup-plugin-peer-deps-external");
7
7
  const plugin_babel_1 = require("@rollup/plugin-babel");
8
8
  const path_1 = require("path");
9
- const rxjs_1 = require("rxjs");
10
- const operators_1 = require("rxjs/operators");
11
- const rxjs_for_await_1 = require("@nx/devkit/src/utils/rxjs-for-await");
12
9
  const autoprefixer = require("autoprefixer");
13
10
  const devkit_1 = require("@nx/devkit");
14
11
  const buildable_libs_utils_1 = require("@nx/js/src/utils/buildable-libs-utils");
15
12
  const plugin_node_resolve_1 = require("@rollup/plugin-node-resolve");
16
- const run_rollup_1 = require("./lib/run-rollup");
13
+ const type_definitions_1 = require("@nx/js/src/plugins/rollup/type-definitions");
17
14
  const normalize_1 = require("./lib/normalize");
18
15
  const analyze_plugin_1 = require("./lib/analyze-plugin");
19
16
  const fs_1 = require("../../utils/fs");
20
17
  const swc_plugin_1 = require("./lib/swc-plugin");
21
18
  const update_package_json_1 = require("./lib/update-package-json");
22
- const type_definitions_1 = require("@nx/js/src/plugins/rollup/type-definitions");
19
+ const config_utils_1 = require("@nx/devkit/src/utils/config-utils");
20
+ const async_iterable_1 = require("@nx/devkit/src/utils/async-iterable");
23
21
  // These use require because the ES import isn't correct.
24
22
  const commonjs = require('@rollup/plugin-commonjs');
25
23
  const image = require('@rollup/plugin-image');
@@ -31,17 +29,18 @@ async function* rollupExecutor(rawOptions, context) {
31
29
  process.env.NODE_ENV ??= 'production';
32
30
  const project = context.projectsConfigurations.projects[context.projectName];
33
31
  const sourceRoot = project.sourceRoot;
34
- const { target, dependencies } = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(context.taskGraph, context.projectGraph, context.root, context.projectName, context.targetName, context.configurationName, true);
32
+ const { dependencies } = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(context.taskGraph, context.projectGraph, context.root, context.projectName, context.targetName, context.configurationName, true);
35
33
  const options = (0, normalize_1.normalizeRollupExecutorOptions)(rawOptions, context, sourceRoot);
36
34
  const packageJson = (0, devkit_1.readJsonFile)(options.project);
37
35
  const npmDeps = (context.projectGraph.dependencies[context.projectName] ?? [])
38
36
  .filter((d) => d.target.startsWith('npm:'))
39
37
  .map((d) => d.target.slice(4));
40
- const rollupOptions = createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps);
38
+ const rollupOptions = await createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps);
41
39
  const outfile = resolveOutfile(context, options);
42
40
  if (options.watch) {
43
- const watcher = rollup.watch(rollupOptions);
44
- return yield* (0, rxjs_for_await_1.eachValueFrom)(new rxjs_1.Observable((obs) => {
41
+ // region Watch build
42
+ return (0, async_iterable_1.createAsyncIterable)(({ next }) => {
43
+ const watcher = rollup.watch(rollupOptions);
45
44
  watcher.on('event', (data) => {
46
45
  if (data.code === 'START') {
47
46
  devkit_1.logger.info(`Bundling ${context.projectName}...`);
@@ -49,51 +48,54 @@ async function* rollupExecutor(rawOptions, context) {
49
48
  else if (data.code === 'END') {
50
49
  (0, update_package_json_1.updatePackageJson)(options, packageJson);
51
50
  devkit_1.logger.info('Bundle complete. Watching for file changes...');
52
- obs.next({ success: true, outfile });
51
+ next({ success: true, outfile });
53
52
  }
54
53
  else if (data.code === 'ERROR') {
55
54
  devkit_1.logger.error(`Error during bundle: ${data.error.message}`);
56
- obs.next({ success: false });
55
+ next({ success: false });
57
56
  }
58
57
  });
59
- // Teardown logic. Close watcher when unsubscribed.
60
- return () => watcher.close();
61
- }));
58
+ const processExitListener = (signal) => () => {
59
+ watcher.close();
60
+ };
61
+ process.once('SIGTERM', processExitListener);
62
+ process.once('SIGINT', processExitListener);
63
+ process.once('SIGQUIT', processExitListener);
64
+ });
65
+ // endregion
62
66
  }
63
67
  else {
64
- devkit_1.logger.info(`Bundling ${context.projectName}...`);
65
- // Delete output path before bundling
66
- if (options.deleteOutputPath) {
67
- (0, fs_1.deleteOutputDir)(context.root, options.outputPath);
68
+ // region Single build
69
+ try {
70
+ devkit_1.logger.info(`Bundling ${context.projectName}...`);
71
+ // Delete output path before bundling
72
+ if (options.deleteOutputPath) {
73
+ (0, fs_1.deleteOutputDir)(context.root, options.outputPath);
74
+ }
75
+ const start = process.hrtime.bigint();
76
+ const bundle = await rollup.rollup(rollupOptions);
77
+ const output = Array.isArray(rollupOptions.output)
78
+ ? rollupOptions.output
79
+ : [rollupOptions.output];
80
+ for (const o of output) {
81
+ await bundle.write(o);
82
+ }
83
+ const end = process.hrtime.bigint();
84
+ const duration = `${(Number(end - start) / 1_000_000_000).toFixed(2)}s`;
85
+ (0, update_package_json_1.updatePackageJson)(options, packageJson);
86
+ devkit_1.logger.info(`⚡ Done in ${duration}`);
87
+ return { success: true, outfile };
68
88
  }
69
- const start = process.hrtime.bigint();
70
- return (0, rxjs_1.from)(rollupOptions)
71
- .pipe((0, operators_1.concatMap)((opts) => (0, run_rollup_1.runRollup)(opts).pipe((0, operators_1.catchError)((e) => {
72
- devkit_1.logger.error(`Error during bundle: ${e}`);
73
- return (0, rxjs_1.of)({ success: false });
74
- }))), (0, operators_1.scan)((acc, result) => {
75
- if (!acc.success)
76
- return acc;
77
- return result;
78
- }, { success: true, outfile }), (0, operators_1.last)(), (0, operators_1.tap)({
79
- next: (result) => {
80
- if (result.success) {
81
- const end = process.hrtime.bigint();
82
- const duration = `${(Number(end - start) / 1000000000).toFixed(2)}s`;
83
- (0, update_package_json_1.updatePackageJson)(options, packageJson);
84
- devkit_1.logger.info(`⚡ Done in ${duration}`);
85
- }
86
- else {
87
- devkit_1.logger.error(`Bundle failed: ${context.projectName}`);
88
- }
89
- },
90
- }))
91
- .toPromise();
89
+ catch {
90
+ devkit_1.logger.error(`Bundle failed: ${context.projectName}`);
91
+ return { success: false };
92
+ }
93
+ // endregion
92
94
  }
93
95
  }
94
96
  exports.rollupExecutor = rollupExecutor;
95
97
  // -----------------------------------------------------------------------------
96
- function createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps) {
98
+ async function createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps) {
97
99
  const useBabel = options.compiler === 'babel';
98
100
  const useTsc = options.compiler === 'tsc';
99
101
  const useSwc = options.compiler === 'swc';
@@ -103,112 +105,129 @@ function createRollupOptions(options, dependencies, context, packageJson, source
103
105
  if (!options.format || !options.format.length) {
104
106
  options.format = readCompatibleFormats(config);
105
107
  }
106
- return options.format.map((format, idx) => {
107
- // Either we're generating only one format, so we should bundle types
108
- // OR we are generating dual formats, so only bundle types for CJS.
109
- const shouldBundleTypes = options.format.length === 1 || format === 'cjs';
110
- const plugins = [
111
- copy({
112
- targets: convertCopyAssetsToRollupOptions(options.outputPath, options.assets),
113
- }),
114
- image(),
115
- json(),
116
- (useTsc || shouldBundleTypes) &&
117
- require('rollup-plugin-typescript2')({
118
- check: !options.skipTypeCheck,
119
- tsconfig: options.tsConfig,
120
- tsconfigOverride: {
121
- compilerOptions: createTsCompilerOptions(config, dependencies, options),
122
- },
123
- }),
124
- shouldBundleTypes &&
125
- (0, type_definitions_1.typeDefinitions)({
126
- main: options.main,
127
- projectRoot: options.projectRoot,
128
- }),
129
- peerDepsExternal({
130
- packageJsonPath: options.project,
131
- }),
132
- postcss({
133
- inject: true,
134
- extract: options.extractCss,
135
- autoModules: true,
136
- plugins: [autoprefixer],
137
- use: {
138
- less: {
139
- javascriptEnabled: options.javascriptEnabled,
140
- },
141
- },
142
- }),
143
- (0, plugin_node_resolve_1.default)({
144
- preferBuiltins: true,
145
- extensions: fileExtensions,
146
- }),
147
- useSwc && (0, swc_plugin_1.swc)(),
148
- useBabel &&
149
- (0, plugin_babel_1.getBabelInputPlugin)({
150
- // Lets `@nx/js/babel` preset know that we are packaging.
151
- caller: {
152
- // @ts-ignore
153
- // Ignoring type checks for caller since we have custom attributes
154
- isNxPackage: true,
155
- // Always target esnext and let rollup handle cjs
156
- supportsStaticESM: true,
157
- isModern: true,
158
- },
159
- cwd: (0, path_1.join)(context.root, sourceRoot),
160
- rootMode: options.babelUpwardRootMode ? 'upward' : undefined,
161
- babelrc: true,
162
- extensions: fileExtensions,
163
- babelHelpers: 'bundled',
164
- skipPreflightCheck: true,
165
- exclude: /node_modules/,
166
- plugins: [
167
- format === 'esm'
168
- ? undefined
169
- : require.resolve('babel-plugin-transform-async-to-promises'),
170
- ].filter(Boolean),
171
- }),
172
- commonjs(),
173
- (0, analyze_plugin_1.analyze)(),
174
- ];
175
- let externalPackages = [
176
- ...Object.keys(packageJson.dependencies || {}),
177
- ...Object.keys(packageJson.peerDependencies || {}),
178
- ]; // If external is set to none, include all dependencies and peerDependencies in externalPackages
179
- if (options.external === 'all') {
180
- externalPackages = externalPackages
181
- .concat(dependencies.map((d) => d.name))
182
- .concat(npmDeps);
108
+ if (packageJson.type === 'module') {
109
+ if (options.format.includes('cjs')) {
110
+ devkit_1.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.`);
183
111
  }
184
- else if (Array.isArray(options.external) && options.external.length > 0) {
185
- externalPackages = externalPackages.concat(options.external);
112
+ options.format = ['esm'];
113
+ }
114
+ else if (packageJson.type === 'commonjs') {
115
+ if (options.format.includes('esm')) {
116
+ devkit_1.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.`);
186
117
  }
187
- externalPackages = [...new Set(externalPackages)];
188
- const mainEntryFileName = options.outputFileName || options.main;
189
- const input = {};
190
- input[(0, path_1.parse)(mainEntryFileName).name] = options.main;
191
- options.additionalEntryPoints.forEach((entry) => {
192
- input[(0, path_1.parse)(entry).name] = entry;
193
- });
194
- const rollupConfig = {
195
- input,
196
- output: {
197
- format,
198
- dir: `${options.outputPath}`,
199
- name: (0, devkit_1.names)(context.projectName).className,
200
- entryFileNames: `[name].${format}.js`,
201
- chunkFileNames: `[name].${format}.js`,
118
+ options.format = ['cjs'];
119
+ }
120
+ const plugins = [
121
+ copy({
122
+ targets: convertCopyAssetsToRollupOptions(options.outputPath, options.assets),
123
+ }),
124
+ image(),
125
+ json(),
126
+ // Needed to generate type definitions, even if we're using babel or swc.
127
+ require('rollup-plugin-typescript2')({
128
+ check: !options.skipTypeCheck,
129
+ tsconfig: options.tsConfig,
130
+ tsconfigOverride: {
131
+ compilerOptions: createTsCompilerOptions(config, dependencies, options),
202
132
  },
203
- external: (id) => {
204
- return externalPackages.some((name) => id === name || id.startsWith(`${name}/`)); // Could be a deep import
133
+ }),
134
+ (0, type_definitions_1.typeDefinitions)({
135
+ main: options.main,
136
+ projectRoot: options.projectRoot,
137
+ }),
138
+ peerDepsExternal({
139
+ packageJsonPath: options.project,
140
+ }),
141
+ postcss({
142
+ inject: true,
143
+ extract: options.extractCss,
144
+ autoModules: true,
145
+ plugins: [autoprefixer],
146
+ use: {
147
+ less: {
148
+ javascriptEnabled: options.javascriptEnabled,
149
+ },
205
150
  },
206
- plugins,
207
- };
208
- return options.rollupConfig.reduce((currentConfig, plugin) => {
209
- return require(plugin)(currentConfig, options);
210
- }, rollupConfig);
151
+ }),
152
+ (0, plugin_node_resolve_1.default)({
153
+ preferBuiltins: true,
154
+ extensions: fileExtensions,
155
+ }),
156
+ useSwc && (0, swc_plugin_1.swc)(),
157
+ useBabel &&
158
+ (0, plugin_babel_1.getBabelInputPlugin)({
159
+ // Lets `@nx/js/babel` preset know that we are packaging.
160
+ caller: {
161
+ // @ts-ignore
162
+ // Ignoring type checks for caller since we have custom attributes
163
+ isNxPackage: true,
164
+ // Always target esnext and let rollup handle cjs
165
+ supportsStaticESM: true,
166
+ isModern: true,
167
+ },
168
+ cwd: (0, path_1.join)(context.root, sourceRoot),
169
+ rootMode: options.babelUpwardRootMode ? 'upward' : undefined,
170
+ babelrc: true,
171
+ extensions: fileExtensions,
172
+ babelHelpers: 'bundled',
173
+ skipPreflightCheck: true, // pre-flight check may yield false positives and also slows down the build
174
+ exclude: /node_modules/,
175
+ }),
176
+ commonjs(),
177
+ (0, analyze_plugin_1.analyze)(),
178
+ ];
179
+ let externalPackages = [
180
+ ...Object.keys(packageJson.dependencies || {}),
181
+ ...Object.keys(packageJson.peerDependencies || {}),
182
+ ]; // If external is set to none, include all dependencies and peerDependencies in externalPackages
183
+ if (options.external === 'all') {
184
+ externalPackages = externalPackages
185
+ .concat(dependencies.map((d) => d.name))
186
+ .concat(npmDeps);
187
+ }
188
+ else if (Array.isArray(options.external) && options.external.length > 0) {
189
+ externalPackages = externalPackages.concat(options.external);
190
+ }
191
+ externalPackages = [...new Set(externalPackages)];
192
+ const mainEntryFileName = options.outputFileName || options.main;
193
+ const input = {};
194
+ input[(0, path_1.parse)(mainEntryFileName).name] = options.main;
195
+ options.additionalEntryPoints.forEach((entry) => {
196
+ input[(0, path_1.parse)(entry).name] = entry;
211
197
  });
198
+ const rollupConfig = {
199
+ input,
200
+ output: options.format.map((format) => ({
201
+ format,
202
+ dir: `${options.outputPath}`,
203
+ name: (0, devkit_1.names)(context.projectName).className,
204
+ entryFileNames: `[name].${format}.js`,
205
+ chunkFileNames: `[name].${format}.js`,
206
+ })),
207
+ external: (id) => {
208
+ return externalPackages.some((name) => id === name || id.startsWith(`${name}/`)); // Could be a deep import
209
+ },
210
+ plugins,
211
+ };
212
+ const userDefinedRollupConfigs = options.rollupConfig.map((plugin) => (0, config_utils_1.loadConfigFile)(plugin));
213
+ let finalConfig = rollupConfig;
214
+ for (const _config of userDefinedRollupConfigs) {
215
+ const config = await _config;
216
+ if (typeof config === 'function') {
217
+ finalConfig = config(finalConfig, options);
218
+ }
219
+ else {
220
+ finalConfig = {
221
+ ...finalConfig,
222
+ ...config,
223
+ plugins: [
224
+ ...(finalConfig.plugins?.length > 0 ? finalConfig.plugins : []),
225
+ ...(config.plugins?.length > 0 ? config.plugins : []),
226
+ ],
227
+ };
228
+ }
229
+ }
230
+ return finalConfig;
212
231
  }
213
232
  exports.createRollupOptions = createRollupOptions;
214
233
  function createTsCompilerOptions(config, dependencies, options) {
@@ -1,4 +1,4 @@
1
- import type { Tree } from '@nx/devkit';
1
+ import { Tree, GeneratorCallback } from '@nx/devkit';
2
2
  import { RollupProjectSchema } from './schema';
3
- export declare function configurationGenerator(tree: Tree, options: RollupProjectSchema): Promise<import("@nx/devkit").GeneratorCallback>;
3
+ export declare function configurationGenerator(tree: Tree, options: RollupProjectSchema): Promise<GeneratorCallback>;
4
4
  export default configurationGenerator;
@@ -4,16 +4,21 @@ exports.configurationGenerator = void 0;
4
4
  const devkit_1 = require("@nx/devkit");
5
5
  const get_import_path_1 = require("@nx/js/src/utils/get-import-path");
6
6
  const init_1 = require("../init/init");
7
+ const add_build_target_defaults_1 = require("@nx/devkit/src/generators/add-build-target-defaults");
8
+ const ensure_dependencies_1 = require("../../utils/ensure-dependencies");
7
9
  async function configurationGenerator(tree, options) {
8
- const task = await (0, init_1.rollupInitGenerator)(tree, {
9
- ...options,
10
- skipFormat: true,
11
- });
10
+ const tasks = [];
11
+ tasks.push(await (0, init_1.rollupInitGenerator)(tree, { ...options, skipFormat: true }));
12
+ if (!options.skipPackageJson) {
13
+ tasks.push((0, ensure_dependencies_1.ensureDependencies)(tree, options));
14
+ }
12
15
  options.buildTarget ??= 'build';
13
16
  checkForTargetConflicts(tree, options);
14
17
  addBuildTarget(tree, options);
15
- await (0, devkit_1.formatFiles)(tree);
16
- return task;
18
+ if (!options.skipFormat) {
19
+ await (0, devkit_1.formatFiles)(tree);
20
+ }
21
+ return (0, devkit_1.runTasksInSerial)(...tasks);
17
22
  }
18
23
  exports.configurationGenerator = configurationGenerator;
19
24
  function checkForTargetConflicts(tree, options) {
@@ -25,6 +30,7 @@ function checkForTargetConflicts(tree, options) {
25
30
  }
26
31
  }
27
32
  function addBuildTarget(tree, options) {
33
+ (0, add_build_target_defaults_1.addBuildTargetDefaults)(tree, '@nx/rollup:rollup', options.buildTarget);
28
34
  const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
29
35
  const packageJsonPath = (0, devkit_1.joinPathFragments)(project.root, 'package.json');
30
36
  if (!tree.exists(packageJsonPath)) {
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "http://json-schema.org/schema",
2
+ "$schema": "https://json-schema.org/schema",
3
3
  "$id": "NxRollupProject",
4
4
  "cli": "nx",
5
5
  "title": "Add Rollup Configuration to a project",
@@ -2,23 +2,38 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.rollupInitGenerator = void 0;
4
4
  const devkit_1 = require("@nx/devkit");
5
- const versions_1 = require("@nx/js/src/utils/versions");
6
- const versions_2 = require("../../utils/versions");
5
+ const versions_1 = require("../../utils/versions");
6
+ const update_package_scripts_1 = require("@nx/devkit/src/utils/update-package-scripts");
7
+ const plugin_1 = require("../../plugins/plugin");
8
+ function addPlugin(tree) {
9
+ const nxJson = (0, devkit_1.readNxJson)(tree);
10
+ nxJson.plugins ??= [];
11
+ for (const plugin of nxJson.plugins) {
12
+ if (typeof plugin === 'string'
13
+ ? plugin === '@nx/rollup/plugin'
14
+ : plugin.plugin === '@nx/rollup/plugin') {
15
+ return;
16
+ }
17
+ }
18
+ nxJson.plugins.push({
19
+ plugin: '@nx/rollup/plugin',
20
+ options: {
21
+ buildTargetName: 'build',
22
+ },
23
+ });
24
+ (0, devkit_1.updateNxJson)(tree, nxJson);
25
+ }
7
26
  async function rollupInitGenerator(tree, schema) {
8
- let task;
9
- if (schema.compiler === 'swc') {
10
- task = (0, devkit_1.addDependenciesToPackageJson)(tree, {}, {
11
- '@nx/rollup': versions_2.nxVersion,
12
- '@swc/helpers': versions_1.swcHelpersVersion,
13
- '@swc/core': versions_1.swcCoreVersion,
14
- 'swc-loader': versions_2.swcLoaderVersion,
15
- });
27
+ let task = () => { };
28
+ if (!schema.skipPackageJson) {
29
+ task = (0, devkit_1.addDependenciesToPackageJson)(tree, {}, { '@nx/rollup': versions_1.nxVersion }, undefined, schema.keepExistingVersions);
30
+ }
31
+ schema.addPlugin ??= process.env.NX_ADD_PLUGINS !== 'false';
32
+ if (schema.addPlugin) {
33
+ addPlugin(tree);
16
34
  }
17
- else {
18
- task = (0, devkit_1.addDependenciesToPackageJson)(tree, {}, {
19
- '@nx/rollup': versions_2.nxVersion,
20
- tslib: versions_2.tsLibVersion,
21
- });
35
+ if (schema.updatePackageScripts) {
36
+ await (0, update_package_scripts_1.updatePackageScripts)(tree, plugin_1.createNodes);
22
37
  }
23
38
  if (!schema.skipFormat) {
24
39
  await (0, devkit_1.formatFiles)(tree);
@@ -1,4 +1,7 @@
1
1
  export interface Schema {
2
- compiler?: 'babel' | 'swc' | 'tsc';
3
2
  skipFormat?: boolean;
3
+ skipPackageJson?: boolean;
4
+ keepExistingVersions?: boolean;
5
+ updatePackageScripts?: boolean;
6
+ addPlugin?: boolean;
4
7
  }
@@ -1,21 +1,32 @@
1
1
  {
2
- "$schema": "http://json-schema.org/schema",
2
+ "$schema": "https://json-schema.org/schema",
3
3
  "$id": "NxWebpackInit",
4
4
  "cli": "nx",
5
5
  "title": "Init Webpack Plugin",
6
6
  "description": "Init Webpack Plugin.",
7
7
  "type": "object",
8
8
  "properties": {
9
- "compiler": {
10
- "type": "string",
11
- "enum": ["babel", "swc", "tsc"],
12
- "description": "The compiler to initialize for.",
13
- "default": "babel"
14
- },
15
9
  "skipFormat": {
16
10
  "description": "Skip formatting files.",
17
11
  "type": "boolean",
18
12
  "default": false
13
+ },
14
+ "skipPackageJson": {
15
+ "description": "Do not add dependencies to `package.json`.",
16
+ "type": "boolean",
17
+ "default": false
18
+ },
19
+ "keepExistingVersions": {
20
+ "type": "boolean",
21
+ "x-priority": "internal",
22
+ "description": "Keep existing dependencies versions",
23
+ "default": false
24
+ },
25
+ "updatePackageScripts": {
26
+ "type": "boolean",
27
+ "x-priority": "internal",
28
+ "description": "Update `package.json` scripts with inferred targets",
29
+ "default": false
19
30
  }
20
31
  },
21
32
  "required": []
@@ -0,0 +1,6 @@
1
+ import { type CreateDependencies, type CreateNodes } from '@nx/devkit';
2
+ export declare const createDependencies: CreateDependencies;
3
+ export interface RollupPluginOptions {
4
+ buildTargetName?: string;
5
+ }
6
+ export declare const createNodes: CreateNodes<RollupPluginOptions>;
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNodes = exports.createDependencies = void 0;
4
+ const cache_directory_1 = require("nx/src/utils/cache-directory");
5
+ const path_1 = require("path");
6
+ const fs_1 = require("fs");
7
+ const devkit_1 = require("@nx/devkit");
8
+ const calculate_hash_for_create_nodes_1 = require("@nx/devkit/src/utils/calculate-hash-for-create-nodes");
9
+ const js_1 = require("@nx/js");
10
+ const get_named_inputs_1 = require("@nx/devkit/src/utils/get-named-inputs");
11
+ const loadConfigFile = require("rollup/dist/loadConfigFile");
12
+ const cachePath = (0, path_1.join)(cache_directory_1.projectGraphCacheDirectory, 'rollup.hash');
13
+ const targetsCache = (0, fs_1.existsSync)(cachePath) ? readTargetsCache() : {};
14
+ const calculatedTargets = {};
15
+ function readTargetsCache() {
16
+ return (0, devkit_1.readJsonFile)(cachePath);
17
+ }
18
+ function writeTargetsToCache(targets) {
19
+ (0, devkit_1.writeJsonFile)(cachePath, targets);
20
+ }
21
+ const createDependencies = () => {
22
+ writeTargetsToCache(calculatedTargets);
23
+ return [];
24
+ };
25
+ exports.createDependencies = createDependencies;
26
+ exports.createNodes = [
27
+ '**/rollup.config.{js,cjs,mjs}',
28
+ async (configFilePath, options, context) => {
29
+ const projectRoot = (0, path_1.dirname)(configFilePath);
30
+ const fullyQualifiedProjectRoot = (0, path_1.join)(context.workspaceRoot, projectRoot);
31
+ // Do not create a project if package.json and project.json do not exist
32
+ const siblingFiles = (0, fs_1.readdirSync)(fullyQualifiedProjectRoot);
33
+ if (!siblingFiles.includes('package.json') &&
34
+ !siblingFiles.includes('project.json')) {
35
+ return {};
36
+ }
37
+ options = normalizeOptions(options);
38
+ const hash = (0, calculate_hash_for_create_nodes_1.calculateHashForCreateNodes)(projectRoot, options, context, [
39
+ (0, js_1.getLockFileName)((0, devkit_1.detectPackageManager)(context.workspaceRoot)),
40
+ ]);
41
+ const targets = targetsCache[hash]
42
+ ? targetsCache[hash]
43
+ : await buildRollupTarget(configFilePath, projectRoot, options, context);
44
+ calculatedTargets[hash] = targets;
45
+ return {
46
+ projects: {
47
+ [projectRoot]: {
48
+ root: projectRoot,
49
+ targets,
50
+ },
51
+ },
52
+ };
53
+ },
54
+ ];
55
+ async function buildRollupTarget(configFilePath, projectRoot, options, context) {
56
+ const namedInputs = (0, get_named_inputs_1.getNamedInputs)(projectRoot, context);
57
+ const rollupConfig = (await loadConfigFile((0, devkit_1.joinPathFragments)(context.workspaceRoot, configFilePath))).options;
58
+ const outputs = getOutputs(rollupConfig, projectRoot);
59
+ const targets = {};
60
+ targets[options.buildTargetName] = {
61
+ command: `rollup -c ${(0, path_1.basename)(configFilePath)}`,
62
+ options: { cwd: projectRoot },
63
+ cache: true,
64
+ dependsOn: [`^${options.buildTargetName}`],
65
+ inputs: [
66
+ ...('production' in namedInputs
67
+ ? ['production', '^production']
68
+ : ['default', '^default']),
69
+ ],
70
+ outputs,
71
+ };
72
+ return targets;
73
+ }
74
+ function getOutputs(rollupConfigs, projectRoot) {
75
+ const outputs = new Set();
76
+ for (const rollupConfig of rollupConfigs) {
77
+ if (rollupConfig.output) {
78
+ const rollupConfigOutputs = [];
79
+ if (Array.isArray(rollupConfig.output)) {
80
+ rollupConfigOutputs.push(...rollupConfig.output);
81
+ }
82
+ else {
83
+ rollupConfigOutputs.push(rollupConfig.output);
84
+ }
85
+ for (const output of rollupConfigOutputs) {
86
+ const outputPathFromConfig = output.dir
87
+ ? output.dir
88
+ : output.file
89
+ ? (0, path_1.dirname)(output.file)
90
+ : 'dist';
91
+ const outputPath = projectRoot === '.'
92
+ ? (0, devkit_1.joinPathFragments)(`{workspaceRoot}`, outputPathFromConfig)
93
+ : (0, devkit_1.joinPathFragments)(`{workspaceRoot}`, projectRoot, outputPathFromConfig);
94
+ outputs.add(outputPath);
95
+ }
96
+ }
97
+ }
98
+ return Array.from(outputs);
99
+ }
100
+ function normalizeOptions(options) {
101
+ options ??= {};
102
+ options.buildTargetName ??= 'build';
103
+ return options;
104
+ }
@@ -0,0 +1,5 @@
1
+ import { type GeneratorCallback, type Tree } from '@nx/devkit';
2
+ export type EnsureDependenciesOptions = {
3
+ compiler?: 'babel' | 'swc' | 'tsc';
4
+ };
5
+ export declare function ensureDependencies(tree: Tree, options: EnsureDependenciesOptions): GeneratorCallback;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ensureDependencies = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const versions_1 = require("@nx/js/src/utils/versions");
6
+ const versions_2 = require("./versions");
7
+ function ensureDependencies(tree, options) {
8
+ switch (options.compiler) {
9
+ case 'swc':
10
+ return (0, devkit_1.addDependenciesToPackageJson)(tree, {}, {
11
+ '@swc/helpers': versions_1.swcHelpersVersion,
12
+ '@swc/core': versions_1.swcCoreVersion,
13
+ 'swc-loader': versions_2.swcLoaderVersion,
14
+ });
15
+ case 'babel':
16
+ return (0, devkit_1.addDependenciesToPackageJson)(tree, {}, {
17
+ 'core-js': versions_2.coreJsVersion, // needed for preset-env to work
18
+ tslib: versions_2.tsLibVersion,
19
+ });
20
+ default:
21
+ return (0, devkit_1.addDependenciesToPackageJson)(tree, {}, { tslib: versions_2.tsLibVersion });
22
+ }
23
+ }
24
+ exports.ensureDependencies = ensureDependencies;
@@ -1,3 +1,4 @@
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 coreJsVersion = "^3.36.1";
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.tsLibVersion = exports.swcLoaderVersion = exports.nxVersion = void 0;
3
+ exports.coreJsVersion = 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.coreJsVersion = '^3.36.1';
@@ -1,4 +0,0 @@
1
- import * as rollup from 'rollup';
2
- export declare function runRollup(options: rollup.RollupOptions): import("rxjs").Observable<{
3
- success: boolean;
4
- }>;
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.runRollup = void 0;
4
- const rollup = require("rollup");
5
- const rxjs_1 = require("rxjs");
6
- const operators_1 = require("rxjs/operators");
7
- function runRollup(options) {
8
- return (0, rxjs_1.from)(rollup.rollup(options)).pipe((0, operators_1.switchMap)((bundle) => {
9
- const outputOptions = Array.isArray(options.output)
10
- ? options.output
11
- : [options.output];
12
- return (0, rxjs_1.from)(Promise.all(outputOptions.map((o) => bundle.write(o))));
13
- }), (0, operators_1.map)(() => ({ success: true })));
14
- }
15
- exports.runRollup = runRollup;