@nx/rollup 19.2.0-beta.4 → 19.2.0-beta.5

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.
Files changed (34) hide show
  1. package/package.json +4 -4
  2. package/src/executors/rollup/lib/normalize.d.ts +2 -5
  3. package/src/executors/rollup/lib/normalize.js +3 -60
  4. package/src/executors/rollup/rollup.impl.d.ts +1 -3
  5. package/src/executors/rollup/rollup.impl.js +7 -176
  6. package/src/generators/configuration/configuration.d.ts +1 -1
  7. package/src/generators/configuration/configuration.js +44 -16
  8. package/src/generators/configuration/schema.d.ts +1 -0
  9. package/src/generators/init/init.js +7 -2
  10. package/src/plugins/delete-output.d.ts +5 -0
  11. package/src/plugins/delete-output.js +11 -0
  12. package/src/plugins/package-json/generate-package-json.d.ts +12 -0
  13. package/src/plugins/package-json/generate-package-json.js +13 -0
  14. package/src/plugins/package-json/update-package-json.d.ts +10 -0
  15. package/src/{executors/rollup/lib → plugins/package-json}/update-package-json.js +11 -10
  16. package/src/plugins/with-nx/get-project-node.d.ts +2 -0
  17. package/src/plugins/with-nx/get-project-node.js +22 -0
  18. package/src/plugins/with-nx/normalize-options.d.ts +2 -0
  19. package/src/plugins/with-nx/normalize-options.js +83 -0
  20. package/src/plugins/with-nx/with-nx-options.d.ts +33 -0
  21. package/src/plugins/with-nx/with-nx-options.js +2 -0
  22. package/src/plugins/with-nx/with-nx.d.ts +4 -0
  23. package/src/plugins/with-nx/with-nx.js +233 -0
  24. package/src/utils/has-plugin.d.ts +2 -0
  25. package/src/utils/has-plugin.js +11 -0
  26. package/src/utils/versions.d.ts +2 -1
  27. package/src/utils/versions.js +3 -2
  28. package/with-nx.d.ts +2 -0
  29. package/with-nx.js +5 -0
  30. package/src/executors/rollup/lib/update-package-json.d.ts +0 -3
  31. /package/src/{executors/rollup/lib/analyze-plugin.d.ts → plugins/analyze.d.ts} +0 -0
  32. /package/src/{executors/rollup/lib/analyze-plugin.js → plugins/analyze.js} +0 -0
  33. /package/src/{executors/rollup/lib/swc-plugin.d.ts → plugins/swc.d.ts} +0 -0
  34. /package/src/{executors/rollup/lib/swc-plugin.js → plugins/swc.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/rollup",
3
- "version": "19.2.0-beta.4",
3
+ "version": "19.2.0-beta.5",
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": {
@@ -43,9 +43,9 @@
43
43
  "rollup-plugin-postcss": "^4.0.2",
44
44
  "rollup-plugin-typescript2": "^0.36.0",
45
45
  "tslib": "^2.3.0",
46
- "@nx/devkit": "19.2.0-beta.4",
47
- "@nx/js": "19.2.0-beta.4",
48
- "@nrwl/rollup": "19.2.0-beta.4"
46
+ "@nx/devkit": "19.2.0-beta.5",
47
+ "@nx/js": "19.2.0-beta.5",
48
+ "@nrwl/rollup": "19.2.0-beta.5"
49
49
  },
50
50
  "publishConfig": {
51
51
  "access": "public"
@@ -1,11 +1,8 @@
1
1
  import { ExecutorContext } from '@nx/devkit';
2
- import type { AssetGlobPattern, RollupExecutorOptions } from '../schema';
2
+ import type { RollupExecutorOptions } from '../schema';
3
3
  export interface NormalizedRollupExecutorOptions extends RollupExecutorOptions {
4
- entryRoot: string;
5
4
  projectRoot: string;
6
- assets: AssetGlobPattern[];
7
5
  rollupConfig: string[];
8
6
  }
9
- export declare function normalizeRollupExecutorOptions(options: RollupExecutorOptions, context: ExecutorContext, sourceRoot: string): NormalizedRollupExecutorOptions;
7
+ export declare function normalizeRollupExecutorOptions(options: RollupExecutorOptions, context: ExecutorContext): NormalizedRollupExecutorOptions;
10
8
  export declare function normalizePluginPath(pluginPath: void | string, root: string): string;
11
- export declare function normalizeAssets(assets: any[], root: string, sourceRoot: string): AssetGlobPattern[];
@@ -1,37 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.normalizeAssets = exports.normalizePluginPath = exports.normalizeRollupExecutorOptions = void 0;
3
+ exports.normalizePluginPath = exports.normalizeRollupExecutorOptions = void 0;
4
4
  const path_1 = require("path");
5
- const fs_1 = require("fs");
6
- const devkit_1 = require("@nx/devkit");
7
- const js_1 = require("@nx/js");
8
- function normalizeRollupExecutorOptions(options, context, sourceRoot) {
5
+ function normalizeRollupExecutorOptions(options, context) {
9
6
  const { root } = context;
10
- const main = `${root}/${options.main}`;
11
- const entryRoot = (0, path_1.dirname)(main);
12
- const project = options.project
13
- ? `${root}/${options.project}`
14
- : (0, path_1.join)(root, 'package.json');
15
- const projectRoot = (0, path_1.dirname)(project);
16
- const outputPath = `${root}/${options.outputPath}`;
17
7
  return {
18
8
  ...options,
19
- // de-dupe formats
20
- format: Array.from(new Set(options.format)),
21
9
  rollupConfig: []
22
10
  .concat(options.rollupConfig)
23
11
  .filter(Boolean)
24
12
  .map((p) => normalizePluginPath(p, root)),
25
- assets: options.assets
26
- ? normalizeAssets(options.assets, root, sourceRoot)
27
- : undefined,
28
- main,
29
- entryRoot,
30
- project,
31
- projectRoot,
32
- outputPath,
13
+ projectRoot: context.projectGraph.nodes[context.projectName].data.root,
33
14
  skipTypeCheck: options.skipTypeCheck || false,
34
- additionalEntryPoints: (0, js_1.createEntryPoints)(options.additionalEntryPoints, context.root),
35
15
  };
36
16
  }
37
17
  exports.normalizeRollupExecutorOptions = normalizeRollupExecutorOptions;
@@ -47,40 +27,3 @@ function normalizePluginPath(pluginPath, root) {
47
27
  }
48
28
  }
49
29
  exports.normalizePluginPath = normalizePluginPath;
50
- function normalizeAssets(assets, root, sourceRoot) {
51
- return assets.map((asset) => {
52
- if (typeof asset === 'string') {
53
- const assetPath = (0, devkit_1.normalizePath)(asset);
54
- const resolvedAssetPath = (0, path_1.resolve)(root, assetPath);
55
- const resolvedSourceRoot = (0, path_1.resolve)(root, sourceRoot);
56
- if (!resolvedAssetPath.startsWith(resolvedSourceRoot)) {
57
- throw new Error(`The ${resolvedAssetPath} asset path must start with the project source root: ${sourceRoot}`);
58
- }
59
- const isDirectory = (0, fs_1.statSync)(resolvedAssetPath).isDirectory();
60
- const input = isDirectory
61
- ? resolvedAssetPath
62
- : (0, path_1.dirname)(resolvedAssetPath);
63
- const output = (0, path_1.relative)(resolvedSourceRoot, (0, path_1.resolve)(root, input));
64
- const glob = isDirectory ? '**/*' : (0, path_1.basename)(resolvedAssetPath);
65
- return {
66
- input,
67
- output,
68
- glob,
69
- };
70
- }
71
- else {
72
- if (asset.output.startsWith('..')) {
73
- throw new Error('An asset cannot be written to a location outside of the output path.');
74
- }
75
- const assetPath = (0, devkit_1.normalizePath)(asset.input);
76
- const resolvedAssetPath = (0, path_1.resolve)(root, assetPath);
77
- return {
78
- ...asset,
79
- input: resolvedAssetPath,
80
- // Now we remove starting slash to make Webpack place it from the output root.
81
- output: asset.output.replace(/^\//, ''),
82
- };
83
- }
84
- });
85
- }
86
- exports.normalizeAssets = normalizeAssets;
@@ -1,9 +1,7 @@
1
1
  import * as rollup from 'rollup';
2
2
  import { type ExecutorContext } from '@nx/devkit';
3
- import { DependentBuildableProjectNode } from '@nx/js/src/utils/buildable-libs-utils';
4
- import type { PackageJson } from 'nx/src/utils/package-json';
5
3
  import { RollupExecutorOptions } from './schema';
6
4
  import { NormalizedRollupExecutorOptions } from './lib/normalize';
7
5
  export declare function rollupExecutor(rawOptions: RollupExecutorOptions, context: ExecutorContext): AsyncGenerator<unknown, any, undefined>;
8
- export declare function createRollupOptions(options: NormalizedRollupExecutorOptions, dependencies: DependentBuildableProjectNode[], context: ExecutorContext, packageJson: PackageJson, sourceRoot: string, npmDeps: string[]): Promise<rollup.RollupOptions | rollup.RollupOptions[]>;
6
+ export declare function createRollupOptions(options: NormalizedRollupExecutorOptions, context: ExecutorContext): Promise<rollup.RollupOptions | rollup.RollupOptions[]>;
9
7
  export default rollupExecutor;
@@ -1,40 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createRollupOptions = exports.rollupExecutor = void 0;
4
- const ts = require("typescript");
5
4
  const rollup = require("rollup");
6
- const plugin_babel_1 = require("@rollup/plugin-babel");
7
5
  const path_1 = require("path");
8
- const autoprefixer = require("autoprefixer");
9
6
  const devkit_1 = require("@nx/devkit");
10
- const buildable_libs_utils_1 = require("@nx/js/src/utils/buildable-libs-utils");
11
- const plugin_node_resolve_1 = require("@rollup/plugin-node-resolve");
12
- const type_definitions_1 = require("@nx/js/src/plugins/rollup/type-definitions");
13
7
  const normalize_1 = require("./lib/normalize");
14
- const analyze_plugin_1 = require("./lib/analyze-plugin");
15
- const fs_1 = require("../../utils/fs");
16
- const swc_plugin_1 = require("./lib/swc-plugin");
17
- const update_package_json_1 = require("./lib/update-package-json");
18
8
  const config_utils_1 = require("@nx/devkit/src/utils/config-utils");
19
9
  const async_iterable_1 = require("@nx/devkit/src/utils/async-iterable");
20
- // These use require because the ES import isn't correct.
21
- const commonjs = require('@rollup/plugin-commonjs');
22
- const image = require('@rollup/plugin-image');
23
- const json = require('@rollup/plugin-json');
24
- const copy = require('rollup-plugin-copy');
25
- const postcss = require('rollup-plugin-postcss');
26
- const fileExtensions = ['.js', '.jsx', '.ts', '.tsx'];
10
+ const with_nx_1 = require("../../plugins/with-nx/with-nx");
11
+ const buildable_libs_utils_1 = require("@nx/js/src/utils/buildable-libs-utils");
27
12
  async function* rollupExecutor(rawOptions, context) {
28
13
  process.env.NODE_ENV ??= 'production';
29
- const project = context.projectsConfigurations.projects[context.projectName];
30
- const sourceRoot = project.sourceRoot;
31
- const { dependencies } = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(context.taskGraph, context.projectGraph, context.root, context.projectName, context.targetName, context.configurationName, true);
32
- const options = (0, normalize_1.normalizeRollupExecutorOptions)(rawOptions, context, sourceRoot);
33
- const packageJson = (0, devkit_1.readJsonFile)(options.project);
34
- const npmDeps = (context.projectGraph.dependencies[context.projectName] ?? [])
35
- .filter((d) => d.target.startsWith('npm:'))
36
- .map((d) => d.target.slice(4));
37
- const rollupOptions = await createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps);
14
+ const options = (0, normalize_1.normalizeRollupExecutorOptions)(rawOptions, context);
15
+ const rollupOptions = await createRollupOptions(options, context);
38
16
  const outfile = resolveOutfile(context, options);
39
17
  if (options.watch) {
40
18
  // region Watch build
@@ -45,7 +23,6 @@ async function* rollupExecutor(rawOptions, context) {
45
23
  devkit_1.logger.info(`Bundling ${context.projectName}...`);
46
24
  }
47
25
  else if (data.code === 'END') {
48
- (0, update_package_json_1.updatePackageJson)(options, packageJson);
49
26
  devkit_1.logger.info('Bundle complete. Watching for file changes...');
50
27
  next({ success: true, outfile });
51
28
  }
@@ -67,10 +44,6 @@ async function* rollupExecutor(rawOptions, context) {
67
44
  // region Single build
68
45
  try {
69
46
  devkit_1.logger.info(`Bundling ${context.projectName}...`);
70
- // Delete output path before bundling
71
- if (options.deleteOutputPath) {
72
- (0, fs_1.deleteOutputDir)(context.root, options.outputPath);
73
- }
74
47
  const start = process.hrtime.bigint();
75
48
  const allRollupOptions = Array.isArray(rollupOptions)
76
49
  ? rollupOptions
@@ -84,7 +57,6 @@ async function* rollupExecutor(rawOptions, context) {
84
57
  }
85
58
  const end = process.hrtime.bigint();
86
59
  const duration = `${(Number(end - start) / 1_000_000_000).toFixed(2)}s`;
87
- (0, update_package_json_1.updatePackageJson)(options, packageJson);
88
60
  devkit_1.logger.info(`⚡ Done in ${duration}`);
89
61
  return { success: true, outfile };
90
62
  }
@@ -104,116 +76,9 @@ async function* rollupExecutor(rawOptions, context) {
104
76
  }
105
77
  exports.rollupExecutor = rollupExecutor;
106
78
  // -----------------------------------------------------------------------------
107
- async function createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps) {
108
- const useBabel = options.compiler === 'babel';
109
- const useSwc = options.compiler === 'swc';
110
- const tsConfigPath = (0, devkit_1.joinPathFragments)(context.root, options.tsConfig);
111
- const configFile = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
112
- const config = ts.parseJsonConfigFileContent(configFile.config, ts.sys, (0, path_1.dirname)(tsConfigPath));
113
- if (!options.format || !options.format.length) {
114
- options.format = readCompatibleFormats(config);
115
- }
116
- if (packageJson.type === 'module') {
117
- if (options.format.includes('cjs')) {
118
- 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.`);
119
- }
120
- options.format = ['esm'];
121
- }
122
- else if (packageJson.type === 'commonjs') {
123
- if (options.format.includes('esm')) {
124
- 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.`);
125
- }
126
- options.format = ['cjs'];
127
- }
128
- const plugins = [
129
- copy({
130
- targets: convertCopyAssetsToRollupOptions(options.outputPath, options.assets),
131
- }),
132
- image(),
133
- json(),
134
- // Needed to generate type definitions, even if we're using babel or swc.
135
- require('rollup-plugin-typescript2')({
136
- check: !options.skipTypeCheck,
137
- tsconfig: options.tsConfig,
138
- tsconfigOverride: {
139
- compilerOptions: createTsCompilerOptions(config, dependencies, options),
140
- },
141
- }),
142
- (0, type_definitions_1.typeDefinitions)({
143
- main: options.main,
144
- projectRoot: options.projectRoot,
145
- }),
146
- postcss({
147
- inject: true,
148
- extract: options.extractCss,
149
- autoModules: true,
150
- plugins: [autoprefixer],
151
- use: {
152
- less: {
153
- javascriptEnabled: options.javascriptEnabled,
154
- },
155
- },
156
- }),
157
- (0, plugin_node_resolve_1.default)({
158
- preferBuiltins: true,
159
- extensions: fileExtensions,
160
- }),
161
- useSwc && (0, swc_plugin_1.swc)(),
162
- useBabel &&
163
- (0, plugin_babel_1.getBabelInputPlugin)({
164
- // Lets `@nx/js/babel` preset know that we are packaging.
165
- caller: {
166
- // @ts-ignore
167
- // Ignoring type checks for caller since we have custom attributes
168
- isNxPackage: true,
169
- // Always target esnext and let rollup handle cjs
170
- supportsStaticESM: true,
171
- isModern: true,
172
- },
173
- cwd: (0, path_1.join)(context.root, sourceRoot),
174
- rootMode: options.babelUpwardRootMode ? 'upward' : undefined,
175
- babelrc: true,
176
- extensions: fileExtensions,
177
- babelHelpers: 'bundled',
178
- skipPreflightCheck: true, // pre-flight check may yield false positives and also slows down the build
179
- exclude: /node_modules/,
180
- }),
181
- commonjs(),
182
- (0, analyze_plugin_1.analyze)(),
183
- ];
184
- let externalPackages = [
185
- ...Object.keys(packageJson.dependencies || {}),
186
- ...Object.keys(packageJson.peerDependencies || {}),
187
- ]; // If external is set to none, include all dependencies and peerDependencies in externalPackages
188
- if (options.external === 'all') {
189
- externalPackages = externalPackages
190
- .concat(dependencies.map((d) => d.name))
191
- .concat(npmDeps);
192
- }
193
- else if (Array.isArray(options.external) && options.external.length > 0) {
194
- externalPackages = externalPackages.concat(options.external);
195
- }
196
- externalPackages = [...new Set(externalPackages)];
197
- const mainEntryFileName = options.outputFileName || options.main;
198
- const input = {};
199
- input[(0, path_1.parse)(mainEntryFileName).name] = options.main;
200
- options.additionalEntryPoints.forEach((entry) => {
201
- input[(0, path_1.parse)(entry).name] = entry;
202
- });
203
- const rollupConfig = {
204
- input,
205
- output: options.format.map((format) => ({
206
- format,
207
- dir: `${options.outputPath}`,
208
- name: (0, devkit_1.names)(context.projectName).className,
209
- entryFileNames: `[name].${format}.js`,
210
- chunkFileNames: `[name].${format}.js`,
211
- })),
212
- external: (id) => {
213
- return externalPackages.some((name) => id === name || id.startsWith(`${name}/`)); // Could be a deep import
214
- },
215
- plugins,
216
- };
79
+ async function createRollupOptions(options, context) {
80
+ const { dependencies } = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(context.taskGraph, context.projectGraph, context.root, context.projectName, context.targetName, context.configurationName, true);
81
+ const rollupConfig = (0, with_nx_1.withNx)(options, {}, dependencies);
217
82
  const userDefinedRollupConfigs = options.rollupConfig.map((plugin) => (0, config_utils_1.loadConfigFile)(plugin));
218
83
  let finalConfig = rollupConfig;
219
84
  for (const _config of userDefinedRollupConfigs) {
@@ -238,40 +103,6 @@ async function createRollupOptions(options, dependencies, context, packageJson,
238
103
  return finalConfig;
239
104
  }
240
105
  exports.createRollupOptions = createRollupOptions;
241
- function createTsCompilerOptions(config, dependencies, options) {
242
- const compilerOptionPaths = (0, buildable_libs_utils_1.computeCompilerOptionsPaths)(config, dependencies);
243
- const compilerOptions = {
244
- rootDir: options.projectRoot,
245
- allowJs: options.allowJs,
246
- declaration: true,
247
- paths: compilerOptionPaths,
248
- };
249
- if (config.options.module === ts.ModuleKind.CommonJS) {
250
- compilerOptions['module'] = 'ESNext';
251
- }
252
- if (options.compiler === 'swc') {
253
- compilerOptions['emitDeclarationOnly'] = true;
254
- }
255
- return compilerOptions;
256
- }
257
- function convertCopyAssetsToRollupOptions(outputPath, assets) {
258
- return assets
259
- ? assets.map((a) => ({
260
- src: (0, path_1.join)(a.input, a.glob).replace(/\\/g, '/'),
261
- dest: (0, path_1.join)(outputPath, a.output).replace(/\\/g, '/'),
262
- }))
263
- : undefined;
264
- }
265
- function readCompatibleFormats(config) {
266
- switch (config.options.module) {
267
- case ts.ModuleKind.CommonJS:
268
- case ts.ModuleKind.UMD:
269
- case ts.ModuleKind.AMD:
270
- return ['cjs'];
271
- default:
272
- return ['esm'];
273
- }
274
- }
275
106
  function resolveOutfile(context, options) {
276
107
  if (!options.format?.includes('cjs'))
277
108
  return undefined;
@@ -1,4 +1,4 @@
1
- import { Tree, GeneratorCallback } from '@nx/devkit';
1
+ import { GeneratorCallback, Tree } from '@nx/devkit';
2
2
  import { RollupProjectSchema } from './schema';
3
3
  export declare function configurationGenerator(tree: Tree, options: RollupProjectSchema): Promise<GeneratorCallback>;
4
4
  export default configurationGenerator;
@@ -6,21 +6,56 @@ const get_import_path_1 = require("@nx/js/src/utils/get-import-path");
6
6
  const init_1 = require("../init/init");
7
7
  const add_build_target_defaults_1 = require("@nx/devkit/src/generators/add-build-target-defaults");
8
8
  const ensure_dependencies_1 = require("../../utils/ensure-dependencies");
9
+ const has_plugin_1 = require("../../utils/has-plugin");
9
10
  async function configurationGenerator(tree, options) {
10
11
  const tasks = [];
12
+ const nxJson = (0, devkit_1.readNxJson)(tree);
13
+ const addPluginDefault = process.env.NX_ADD_PLUGINS !== 'false' &&
14
+ nxJson.useInferencePlugins !== false;
15
+ options.addPlugin ??= addPluginDefault;
11
16
  tasks.push(await (0, init_1.rollupInitGenerator)(tree, { ...options, skipFormat: true }));
12
17
  if (!options.skipPackageJson) {
13
18
  tasks.push((0, ensure_dependencies_1.ensureDependencies)(tree, options));
14
19
  }
15
- options.buildTarget ??= 'build';
16
- checkForTargetConflicts(tree, options);
17
- addBuildTarget(tree, options);
20
+ if ((0, has_plugin_1.hasPlugin)(tree)) {
21
+ createRollupConfig(tree, options);
22
+ }
23
+ else {
24
+ options.buildTarget ??= 'build';
25
+ checkForTargetConflicts(tree, options);
26
+ addBuildTarget(tree, options);
27
+ }
28
+ addPackageJson(tree, options);
18
29
  if (!options.skipFormat) {
19
30
  await (0, devkit_1.formatFiles)(tree);
20
31
  }
21
32
  return (0, devkit_1.runTasksInSerial)(...tasks);
22
33
  }
23
34
  exports.configurationGenerator = configurationGenerator;
35
+ function createRollupConfig(tree, options) {
36
+ const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
37
+ const buildOptions = {
38
+ outputPath: (0, devkit_1.joinPathFragments)((0, devkit_1.offsetFromRoot)(project.root), 'dist', project.root === '.' ? project.name : project.root),
39
+ compiler: options.compiler ?? 'babel',
40
+ main: options.main ?? './src/index.ts',
41
+ tsConfig: options.tsConfig ?? './tsconfig.lib.json',
42
+ };
43
+ tree.write((0, devkit_1.joinPathFragments)(project.root, 'rollup.config.js'), (0, devkit_1.stripIndents) `
44
+ const { withNx } = require('@nx/rollup/with-nx');
45
+
46
+ module.exports = withNx({
47
+ main: '${buildOptions.main}',
48
+ outputPath: '${buildOptions.outputPath}',
49
+ tsConfig: '${buildOptions.tsConfig}',
50
+ compiler: '${buildOptions.compiler}',
51
+ format: ${JSON.stringify(options.format ?? ['esm'])},
52
+ assets:[{ input: '.', output: '.', glob:'*.md'}],
53
+ }, {
54
+ // Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
55
+ // e.g.
56
+ // output: { sourcemap: true },
57
+ });`);
58
+ }
24
59
  function checkForTargetConflicts(tree, options) {
25
60
  if (options.skipValidation)
26
61
  return;
@@ -29,8 +64,7 @@ function checkForTargetConflicts(tree, options) {
29
64
  throw new Error(`Project "${options.project}" already has a ${options.buildTarget} target. Pass --skipValidation to ignore this error.`);
30
65
  }
31
66
  }
32
- function addBuildTarget(tree, options) {
33
- (0, add_build_target_defaults_1.addBuildTargetDefaults)(tree, '@nx/rollup:rollup', options.buildTarget);
67
+ function addPackageJson(tree, options) {
34
68
  const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
35
69
  const packageJsonPath = (0, devkit_1.joinPathFragments)(project.root, 'package.json');
36
70
  if (!tree.exists(packageJsonPath)) {
@@ -40,11 +74,15 @@ function addBuildTarget(tree, options) {
40
74
  version: '0.0.1',
41
75
  });
42
76
  }
77
+ }
78
+ function addBuildTarget(tree, options) {
79
+ (0, add_build_target_defaults_1.addBuildTargetDefaults)(tree, '@nx/rollup:rollup', options.buildTarget);
80
+ const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
43
81
  const prevBuildOptions = project.targets?.[options.buildTarget]?.options;
44
82
  const buildOptions = {
45
83
  main: options.main ??
46
84
  prevBuildOptions?.main ??
47
- (0, devkit_1.joinPathFragments)(project.root, 'src/main.ts'),
85
+ (0, devkit_1.joinPathFragments)(project.root, 'src/index.ts'),
48
86
  outputPath: prevBuildOptions?.outputPath ??
49
87
  (0, devkit_1.joinPathFragments)('dist', project.root === '.' ? project.name : project.root),
50
88
  tsConfig: options.tsConfig ??
@@ -76,17 +114,7 @@ function addBuildTarget(tree, options) {
76
114
  [options.buildTarget]: {
77
115
  executor: '@nx/rollup:rollup',
78
116
  outputs: ['{options.outputPath}'],
79
- defaultConfiguration: 'production',
80
117
  options: buildOptions,
81
- configurations: {
82
- production: {
83
- optimization: true,
84
- sourceMap: false,
85
- namedChunks: false,
86
- extractLicenses: true,
87
- vendorChunk: false,
88
- },
89
- },
90
118
  },
91
119
  },
92
120
  });
@@ -11,4 +11,5 @@ export interface RollupProjectSchema {
11
11
  rollupConfig?: string;
12
12
  buildTarget?: string;
13
13
  format?: ('cjs' | 'esm')[];
14
+ addPlugin?: boolean;
14
15
  }
@@ -7,10 +7,15 @@ const add_plugin_1 = require("@nx/devkit/src/utils/add-plugin");
7
7
  const plugin_1 = require("../../plugins/plugin");
8
8
  async function rollupInitGenerator(tree, schema) {
9
9
  let task = () => { };
10
+ schema.addPlugin ??= process.env.NX_ADD_PLUGINS !== 'false';
10
11
  if (!schema.skipPackageJson) {
11
- task = (0, devkit_1.addDependenciesToPackageJson)(tree, {}, { '@nx/rollup': versions_1.nxVersion }, undefined, schema.keepExistingVersions);
12
+ const devDependencies = { '@nx/rollup': versions_1.nxVersion };
13
+ if (schema.addPlugin) {
14
+ // Ensure user can run Rollup CLI.
15
+ devDependencies['rollup'] = versions_1.rollupVersion;
16
+ }
17
+ task = (0, devkit_1.addDependenciesToPackageJson)(tree, {}, devDependencies, undefined, schema.keepExistingVersions);
12
18
  }
13
- schema.addPlugin ??= process.env.NX_ADD_PLUGINS !== 'false';
14
19
  if (schema.addPlugin) {
15
20
  await (0, add_plugin_1.addPluginV1)(tree, await (0, devkit_1.createProjectGraphAsync)(), '@nx/rollup/plugin', plugin_1.createNodes, {
16
21
  buildTargetName: ['build', 'rollup:build', 'rollup-build'],
@@ -0,0 +1,5 @@
1
+ import type { Plugin } from 'rollup';
2
+ export interface DeleteOutputOptions {
3
+ dirs: string[];
4
+ }
5
+ export declare function deleteOutput(options: DeleteOutputOptions): Plugin;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteOutput = void 0;
4
+ const fs_1 = require("../utils/fs");
5
+ function deleteOutput(options) {
6
+ return {
7
+ name: 'rollup-plugin-nx-delete-output',
8
+ buildStart: () => options.dirs.forEach((dir) => (0, fs_1.deleteOutputDir)(process.cwd(), dir)),
9
+ };
10
+ }
11
+ exports.deleteOutput = deleteOutput;
@@ -0,0 +1,12 @@
1
+ import type { Plugin } from 'rollup';
2
+ import type { PackageJson } from 'nx/src/utils/package-json';
3
+ export interface GeneratePackageJsonOptions {
4
+ outputPath: string;
5
+ main: string;
6
+ format: string[];
7
+ generateExportsField?: boolean;
8
+ skipTypeField?: boolean;
9
+ outputFileName?: string;
10
+ additionalEntryPoints?: string[];
11
+ }
12
+ export declare function generatePackageJson(options: GeneratePackageJsonOptions, packageJson: PackageJson): Plugin;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generatePackageJson = void 0;
4
+ const update_package_json_1 = require("./update-package-json");
5
+ function generatePackageJson(options, packageJson) {
6
+ return {
7
+ name: 'rollup-plugin-nx-generate-package-json',
8
+ writeBundle: () => {
9
+ (0, update_package_json_1.updatePackageJson)(options, packageJson);
10
+ },
11
+ };
12
+ }
13
+ exports.generatePackageJson = generatePackageJson;
@@ -0,0 +1,10 @@
1
+ import { PackageJson } from 'nx/src/utils/package-json';
2
+ export declare function updatePackageJson(options: {
3
+ outputPath: string;
4
+ main: string;
5
+ format: string[];
6
+ generateExportsField?: boolean;
7
+ skipTypeField?: boolean;
8
+ outputFileName?: string;
9
+ additionalEntryPoints?: string[];
10
+ }, packageJson: PackageJson): void;
@@ -5,7 +5,6 @@ const path_1 = require("path");
5
5
  const fileutils_1 = require("nx/src/utils/fileutils");
6
6
  const fs_1 = require("fs");
7
7
  const devkit_1 = require("@nx/devkit");
8
- // TODO(jack): Use updatePackageJson from @nx/js instead.
9
8
  function updatePackageJson(options, packageJson) {
10
9
  const hasEsmFormat = options.format.includes('esm');
11
10
  const hasCjsFormat = options.format.includes('cjs');
@@ -59,8 +58,8 @@ function updatePackageJson(options, packageJson) {
59
58
  // Make sure both ESM and CJS point to same instance of the package because libs like React, RxJS, etc. requires it.
60
59
  // Also need a special .cjs.default.js file that re-exports the `default` from CJS, or else
61
60
  // default import in Node will not work.
62
- (0, fs_1.writeFileSync)((0, path_1.join)(options.outputPath, filePath.replace(/\.cjs\.js$/, '.cjs.default.js')), `exports._default = require('./${(0, path_1.parse)(filePath).base}').default;`);
63
- (0, fs_1.writeFileSync)((0, path_1.join)(options.outputPath, fauxEsmFilePath),
61
+ (0, fs_1.writeFileSync)((0, path_1.join)(devkit_1.workspaceRoot, options.outputPath, filePath.replace(/\.cjs\.js$/, '.cjs.default.js')), `exports._default = require('./${(0, path_1.parse)(filePath).base}').default;`);
62
+ (0, fs_1.writeFileSync)((0, path_1.join)(devkit_1.workspaceRoot, options.outputPath, fauxEsmFilePath),
64
63
  // Re-export from relative CJS file, and Node will synthetically export it as ESM.
65
64
  (0, devkit_1.stripIndents) `
66
65
  export * from './${relativeFile}';
@@ -73,16 +72,18 @@ function updatePackageJson(options, packageJson) {
73
72
  }
74
73
  }
75
74
  }
76
- (0, fileutils_1.writeJsonFile)(`${options.outputPath}/package.json`, packageJson);
75
+ (0, fileutils_1.writeJsonFile)((0, path_1.join)(devkit_1.workspaceRoot, options.outputPath, 'package.json'), packageJson);
77
76
  }
78
77
  exports.updatePackageJson = updatePackageJson;
79
78
  function getExports(options) {
80
- const mainFile = options.outputFileName
81
- ? options.outputFileName.replace(/\.[tj]s$/, '')
82
- : (0, path_1.basename)(options.main).replace(/\.[tj]s$/, '');
83
- const exports = {
84
- '.': './' + mainFile + options.fileExt,
85
- };
79
+ const exports = {};
80
+ // Users may provide custom input option and skip the main field.
81
+ if (options.main) {
82
+ const mainFile = options.outputFileName
83
+ ? options.outputFileName.replace(/\.[tj]s$/, '')
84
+ : (0, path_1.basename)(options.main).replace(/\.[tj]s$/, '');
85
+ exports['.'] = './' + mainFile + options.fileExt;
86
+ }
86
87
  if (options.additionalEntryPoints) {
87
88
  for (const file of options.additionalEntryPoints) {
88
89
  const { name: fileName } = (0, path_1.parse)(file);
@@ -0,0 +1,2 @@
1
+ import { ProjectGraphProjectNode } from '@nx/devkit';
2
+ export declare function getProjectNode(): ProjectGraphProjectNode;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getProjectNode = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ function getProjectNode() {
6
+ // During graph construction, project is not necessary. Return a stub.
7
+ if (global.NX_GRAPH_CREATION) {
8
+ return {
9
+ type: 'lib',
10
+ name: '',
11
+ data: {
12
+ root: '',
13
+ },
14
+ };
15
+ }
16
+ else {
17
+ const projectGraph = (0, devkit_1.readCachedProjectGraph)();
18
+ const projectName = process.env.NX_TASK_TARGET_PROJECT;
19
+ return projectGraph.nodes[projectName];
20
+ }
21
+ }
22
+ exports.getProjectNode = getProjectNode;
@@ -0,0 +1,2 @@
1
+ import type { NormalizedRollupWithNxPluginOptions, RollupWithNxPluginOptions } from './with-nx-options';
2
+ export declare function normalizeOptions(projectRoot: string, sourceRoot: string, options: RollupWithNxPluginOptions): NormalizedRollupWithNxPluginOptions;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeOptions = void 0;
4
+ const node_path_1 = require("node:path");
5
+ const node_fs_1 = require("node:fs");
6
+ const devkit_1 = require("@nx/devkit");
7
+ const js_1 = require("@nx/js");
8
+ function normalizeOptions(projectRoot, sourceRoot, options) {
9
+ if (global.NX_GRAPH_CREATION)
10
+ return options;
11
+ normalizeRelativePaths(projectRoot, options);
12
+ return {
13
+ ...options,
14
+ additionalEntryPoints: (0, js_1.createEntryPoints)(options.additionalEntryPoints, devkit_1.workspaceRoot),
15
+ allowJs: options.allowJs ?? false,
16
+ assets: options.assets
17
+ ? normalizeAssets(options.assets, devkit_1.workspaceRoot, sourceRoot)
18
+ : [],
19
+ babelUpwardRootMode: options.babelUpwardRootMode ?? false,
20
+ compiler: options.compiler ?? 'babel',
21
+ deleteOutputPath: options.deleteOutputPath ?? true,
22
+ extractCss: options.extractCss ?? true,
23
+ format: options.format ? Array.from(new Set(options.format)) : undefined,
24
+ generateExportsField: options.generateExportsField ?? false,
25
+ javascriptEnabled: options.javascriptEnabled ?? false,
26
+ skipTypeCheck: options.skipTypeCheck ?? false,
27
+ skipTypeField: options.skipTypeField ?? false,
28
+ };
29
+ }
30
+ exports.normalizeOptions = normalizeOptions;
31
+ function normalizeAssets(assets, root, sourceRoot) {
32
+ return assets.map((asset) => {
33
+ if (typeof asset === 'string') {
34
+ const assetPath = (0, devkit_1.normalizePath)(asset);
35
+ const resolvedAssetPath = (0, node_path_1.resolve)(root, assetPath);
36
+ const resolvedSourceRoot = (0, node_path_1.resolve)(root, sourceRoot);
37
+ if (!resolvedAssetPath.startsWith(resolvedSourceRoot)) {
38
+ throw new Error(`The ${resolvedAssetPath} asset path must start with the project source root: ${sourceRoot}`);
39
+ }
40
+ const isDirectory = (0, node_fs_1.statSync)(resolvedAssetPath).isDirectory();
41
+ const input = isDirectory
42
+ ? resolvedAssetPath
43
+ : (0, node_path_1.dirname)(resolvedAssetPath);
44
+ const output = (0, node_path_1.relative)(resolvedSourceRoot, (0, node_path_1.resolve)(root, input));
45
+ const glob = isDirectory ? '**/*' : (0, node_path_1.basename)(resolvedAssetPath);
46
+ return {
47
+ input,
48
+ output,
49
+ glob,
50
+ };
51
+ }
52
+ else {
53
+ if (asset.output.startsWith('..')) {
54
+ throw new Error('An asset cannot be written to a location outside of the output path.');
55
+ }
56
+ const assetPath = (0, devkit_1.normalizePath)(asset.input);
57
+ const resolvedAssetPath = (0, node_path_1.resolve)(root, assetPath);
58
+ return {
59
+ ...asset,
60
+ input: resolvedAssetPath,
61
+ // Now we remove starting slash to make Webpack place it from the output root.
62
+ output: asset.output.replace(/^\//, ''),
63
+ };
64
+ }
65
+ });
66
+ }
67
+ function normalizeRelativePaths(projectRoot, options) {
68
+ for (const [fieldName, fieldValue] of Object.entries(options)) {
69
+ if (isRelativePath(fieldValue)) {
70
+ options[fieldName] = (0, node_path_1.join)(projectRoot, fieldValue);
71
+ }
72
+ else if (Array.isArray(fieldValue)) {
73
+ for (let i = 0; i < fieldValue.length; i++) {
74
+ if (isRelativePath(fieldValue[i])) {
75
+ fieldValue[i] = (0, node_path_1.join)(projectRoot, fieldValue[i]);
76
+ }
77
+ }
78
+ }
79
+ }
80
+ }
81
+ function isRelativePath(val) {
82
+ return typeof val === 'string' && val.startsWith('.');
83
+ }
@@ -0,0 +1,33 @@
1
+ export interface RollupWithNxPluginOptions {
2
+ additionalEntryPoints?: string[];
3
+ allowJs?: boolean;
4
+ assets?: any[];
5
+ babelUpwardRootMode?: boolean;
6
+ compiler?: 'babel' | 'tsc' | 'swc';
7
+ deleteOutputPath?: boolean;
8
+ external?: string[] | 'all' | 'none';
9
+ extractCss?: boolean | string;
10
+ format?: ('cjs' | 'esm')[];
11
+ generateExportsField?: boolean;
12
+ javascriptEnabled?: boolean;
13
+ main: string;
14
+ /** @deprecated Do not set this. The package.json file in project root is detected automatically. */
15
+ project?: string;
16
+ outputFileName?: string;
17
+ outputPath: string;
18
+ rollupConfig?: string | string[];
19
+ skipTypeCheck?: boolean;
20
+ skipTypeField?: boolean;
21
+ tsConfig: string;
22
+ }
23
+ export interface AssetGlobPattern {
24
+ glob: string;
25
+ ignore?: string[];
26
+ input: string;
27
+ output: string;
28
+ }
29
+ export interface NormalizedRollupWithNxPluginOptions extends RollupWithNxPluginOptions {
30
+ assets: AssetGlobPattern[];
31
+ compiler: 'babel' | 'tsc' | 'swc';
32
+ format: ('cjs' | 'esm')[];
33
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import * as rollup from 'rollup';
2
+ import { DependentBuildableProjectNode } from '@nx/js/src/utils/buildable-libs-utils';
3
+ import { RollupWithNxPluginOptions } from './with-nx-options';
4
+ export declare function withNx(rawOptions: RollupWithNxPluginOptions, rollupConfig?: rollup.RollupOptions, dependencies?: DependentBuildableProjectNode[]): rollup.RollupOptions;
@@ -0,0 +1,233 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withNx = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const ts = require("typescript");
7
+ const plugin_babel_1 = require("@rollup/plugin-babel");
8
+ const autoprefixer = require("autoprefixer");
9
+ const devkit_1 = require("@nx/devkit");
10
+ const buildable_libs_utils_1 = require("@nx/js/src/utils/buildable-libs-utils");
11
+ const plugin_node_resolve_1 = require("@rollup/plugin-node-resolve");
12
+ const type_definitions_1 = require("@nx/js/src/plugins/rollup/type-definitions");
13
+ const analyze_1 = require("../analyze");
14
+ const swc_1 = require("../swc");
15
+ const generate_package_json_1 = require("../package-json/generate-package-json");
16
+ const get_project_node_1 = require("./get-project-node");
17
+ const delete_output_1 = require("../delete-output");
18
+ const normalize_options_1 = require("./normalize-options");
19
+ // These use require because the ES import isn't correct.
20
+ const commonjs = require('@rollup/plugin-commonjs');
21
+ const image = require('@rollup/plugin-image');
22
+ const json = require('@rollup/plugin-json');
23
+ const copy = require('rollup-plugin-copy');
24
+ const postcss = require('rollup-plugin-postcss');
25
+ const fileExtensions = ['.js', '.jsx', '.ts', '.tsx'];
26
+ function withNx(rawOptions, rollupConfig = {},
27
+ // Passed by @nx/rollup:rollup executor to previous behavior of remapping tsconfig paths based on buildable dependencies remains intact.
28
+ dependencies) {
29
+ const finalConfig = { ...rollupConfig };
30
+ // Since this is invoked by the executor, the graph has already been created and cached.
31
+ const projectNode = (0, get_project_node_1.getProjectNode)();
32
+ const projectRoot = (0, node_path_1.join)(devkit_1.workspaceRoot, projectNode.data.root);
33
+ // Cannot read in graph during construction, but we only need it during build time.
34
+ const projectGraph = global.NX_GRAPH_CREATION
35
+ ? null
36
+ : (0, devkit_1.readCachedProjectGraph)();
37
+ // If dependencies are not passed from executor, calculate them from project graph.
38
+ if (!dependencies && !global.NX_GRAPH_CREATION) {
39
+ const result = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(undefined, projectGraph, devkit_1.workspaceRoot, projectNode.name, process.env.NX_TASK_TARGET_TARGET, process.env.NX_TASK_TARGET_CONFIGURATION, true);
40
+ dependencies = result.dependencies;
41
+ }
42
+ const options = (0, normalize_options_1.normalizeOptions)(projectNode.data.root, projectNode.data.sourceRoot, rawOptions);
43
+ const useBabel = options.compiler === 'babel';
44
+ const useSwc = options.compiler === 'swc';
45
+ const tsConfigPath = (0, devkit_1.joinPathFragments)(devkit_1.workspaceRoot, options.tsConfig);
46
+ const tsConfigFile = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
47
+ const tsConfig = ts.parseJsonConfigFileContent(tsConfigFile.config, ts.sys, (0, node_path_1.dirname)(tsConfigPath));
48
+ if (!options.format || !options.format.length) {
49
+ options.format = readCompatibleFormats(tsConfig);
50
+ }
51
+ if (rollupConfig.input &&
52
+ (options.main || options.additionalEntryPoints.length > 0)) {
53
+ devkit_1.logger.warn(`Setting "input" in rollup config overrides "main" and "additionalEntryPoints" options.`);
54
+ }
55
+ // If user provides their own input, override our defaults.
56
+ finalConfig.input = rollupConfig.input || createInput(options);
57
+ if (options.format) {
58
+ if (Array.isArray(rollupConfig.output)) {
59
+ throw new Error(`Cannot use Rollup array output option and withNx format option together. Use an object instead.`);
60
+ }
61
+ if (rollupConfig.output?.format || rollupConfig.output?.dir) {
62
+ devkit_1.logger.warn(`"output.dir" and "output.format" are overridden by "withNx".`);
63
+ }
64
+ finalConfig.output = options.format.map((format) => ({
65
+ // These options could be overridden by the user, especially if they use a single format.
66
+ entryFileNames: `[name].${format}.js`,
67
+ chunkFileNames: `[name].${format}.js`,
68
+ ...rollupConfig.output,
69
+ // Format and dir cannot be overridden by user or else the behavior will break.
70
+ format,
71
+ dir: global.NX_GRAPH_CREATION
72
+ ? // Options are not normalized with project root during graph creation due to the lack of project and project root.
73
+ // Cannot be joined with workspace root now, but will be handled by @nx/rollup/plugin.
74
+ options.outputPath
75
+ : (0, node_path_1.join)(devkit_1.workspaceRoot, options.outputPath),
76
+ }));
77
+ }
78
+ let packageJson;
79
+ if (!global.NX_GRAPH_CREATION) {
80
+ const packageJsonPath = options.project
81
+ ? (0, node_path_1.join)(devkit_1.workspaceRoot, options.project)
82
+ : (0, node_path_1.join)(projectRoot, 'package.json');
83
+ if (!(0, node_fs_1.existsSync)(packageJsonPath)) {
84
+ throw new Error(`Cannot find ${packageJsonPath}.`);
85
+ }
86
+ packageJson = (0, devkit_1.readJsonFile)(packageJsonPath);
87
+ if (packageJson.type === 'module') {
88
+ if (options.format.includes('cjs')) {
89
+ 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.`);
90
+ }
91
+ options.format = ['esm'];
92
+ }
93
+ else if (packageJson.type === 'commonjs') {
94
+ if (options.format.includes('esm')) {
95
+ 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.`);
96
+ }
97
+ options.format = ['cjs'];
98
+ }
99
+ }
100
+ // User may wish to customize how external behaves by overriding our default.
101
+ if (!rollupConfig.external && !global.NX_GRAPH_CREATION) {
102
+ const npmDeps = (projectGraph.dependencies[projectNode.name] ?? [])
103
+ .filter((d) => d.target.startsWith('npm:'))
104
+ .map((d) => d.target.slice(4));
105
+ let externalPackages = [
106
+ ...Object.keys(packageJson.dependencies || {}),
107
+ ...Object.keys(packageJson.peerDependencies || {}),
108
+ ]; // If external is set to none, include all dependencies and peerDependencies in externalPackages
109
+ if (options.external === 'all') {
110
+ externalPackages = externalPackages.concat(npmDeps);
111
+ }
112
+ else if (Array.isArray(options.external) && options.external.length > 0) {
113
+ externalPackages = externalPackages.concat(options.external);
114
+ }
115
+ externalPackages = [...new Set(externalPackages)];
116
+ finalConfig.external = (id) => {
117
+ return externalPackages.some((name) => id === name || id.startsWith(`${name}/`));
118
+ };
119
+ }
120
+ if (!global.NX_GRAPH_CREATION) {
121
+ finalConfig.plugins = [
122
+ copy({
123
+ targets: convertCopyAssetsToRollupOptions(options.outputPath, options.assets),
124
+ }),
125
+ image(),
126
+ json(),
127
+ // Needed to generate type definitions, even if we're using babel or swc.
128
+ require('rollup-plugin-typescript2')({
129
+ check: !options.skipTypeCheck,
130
+ tsconfig: options.tsConfig,
131
+ tsconfigOverride: {
132
+ compilerOptions: createTsCompilerOptions(projectRoot, tsConfig, options, dependencies),
133
+ },
134
+ }),
135
+ (0, type_definitions_1.typeDefinitions)({
136
+ projectRoot,
137
+ }),
138
+ postcss({
139
+ inject: true,
140
+ extract: options.extractCss,
141
+ autoModules: true,
142
+ plugins: [autoprefixer],
143
+ use: {
144
+ less: {
145
+ javascriptEnabled: options.javascriptEnabled,
146
+ },
147
+ },
148
+ }),
149
+ (0, plugin_node_resolve_1.default)({
150
+ preferBuiltins: true,
151
+ extensions: fileExtensions,
152
+ }),
153
+ useSwc && (0, swc_1.swc)(),
154
+ useBabel &&
155
+ (0, plugin_babel_1.getBabelInputPlugin)({
156
+ // Lets `@nx/js/babel` preset know that we are packaging.
157
+ caller: {
158
+ // @ts-ignore
159
+ // Ignoring type checks for caller since we have custom attributes
160
+ isNxPackage: true,
161
+ // Always target esnext and let rollup handle cjs
162
+ supportsStaticESM: true,
163
+ isModern: true,
164
+ },
165
+ cwd: (0, node_path_1.join)(devkit_1.workspaceRoot, projectNode.data.sourceRoot ?? projectNode.data.root),
166
+ rootMode: options.babelUpwardRootMode ? 'upward' : undefined,
167
+ babelrc: true,
168
+ extensions: fileExtensions,
169
+ babelHelpers: 'bundled',
170
+ skipPreflightCheck: true, // pre-flight check may yield false positives and also slows down the build
171
+ exclude: /node_modules/,
172
+ }),
173
+ commonjs(),
174
+ (0, analyze_1.analyze)(),
175
+ (0, generate_package_json_1.generatePackageJson)(options, packageJson),
176
+ ];
177
+ if (Array.isArray(rollupConfig.plugins)) {
178
+ finalConfig.plugins.push(...rollupConfig.plugins);
179
+ }
180
+ if (options.deleteOutputPath) {
181
+ finalConfig.plugins.push((0, delete_output_1.deleteOutput)({
182
+ dirs: Array.isArray(finalConfig.output)
183
+ ? finalConfig.output.map((o) => o.dir)
184
+ : [finalConfig.output.dir],
185
+ }));
186
+ }
187
+ }
188
+ return finalConfig;
189
+ }
190
+ exports.withNx = withNx;
191
+ function createInput(options) {
192
+ const mainEntryFileName = options.outputFileName || options.main;
193
+ const input = {};
194
+ input[(0, node_path_1.parse)(mainEntryFileName).name] = (0, node_path_1.join)(devkit_1.workspaceRoot, options.main);
195
+ options.additionalEntryPoints?.forEach((entry) => {
196
+ input[(0, node_path_1.parse)(entry).name] = (0, node_path_1.join)(devkit_1.workspaceRoot, entry);
197
+ });
198
+ return input;
199
+ }
200
+ function createTsCompilerOptions(projectRoot, config, options, dependencies) {
201
+ const compilerOptionPaths = (0, buildable_libs_utils_1.computeCompilerOptionsPaths)(config, dependencies ?? []);
202
+ const compilerOptions = {
203
+ rootDir: projectRoot,
204
+ allowJs: options.allowJs,
205
+ declaration: true,
206
+ paths: compilerOptionPaths,
207
+ };
208
+ if (config.options.module === ts.ModuleKind.CommonJS) {
209
+ compilerOptions['module'] = 'ESNext';
210
+ }
211
+ if (options.compiler === 'swc') {
212
+ compilerOptions['emitDeclarationOnly'] = true;
213
+ }
214
+ return compilerOptions;
215
+ }
216
+ function convertCopyAssetsToRollupOptions(outputPath, assets) {
217
+ return assets
218
+ ? assets.map((a) => ({
219
+ src: (0, node_path_1.join)(a.input, a.glob).replace(/\\/g, '/'),
220
+ dest: (0, node_path_1.join)(devkit_1.workspaceRoot, outputPath, a.output).replace(/\\/g, '/'),
221
+ }))
222
+ : undefined;
223
+ }
224
+ function readCompatibleFormats(config) {
225
+ switch (config.options.module) {
226
+ case ts.ModuleKind.CommonJS:
227
+ case ts.ModuleKind.UMD:
228
+ case ts.ModuleKind.AMD:
229
+ return ['cjs'];
230
+ default:
231
+ return ['esm'];
232
+ }
233
+ }
@@ -0,0 +1,2 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export declare function hasPlugin(tree: Tree): boolean;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasPlugin = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ function hasPlugin(tree) {
6
+ const nxJson = (0, devkit_1.readNxJson)(tree);
7
+ return !!nxJson.plugins?.some((p) => typeof p === 'string'
8
+ ? p === '@nx/rollup/plugin'
9
+ : p.plugin === '@nx/rollup/plugin');
10
+ }
11
+ exports.hasPlugin = hasPlugin;
@@ -1,4 +1,5 @@
1
1
  export declare const nxVersion: any;
2
+ export declare const coreJsVersion = "^3.36.1";
3
+ export declare const rollupVersion = "^4.14.0";
2
4
  export declare const swcLoaderVersion = "0.1.15";
3
5
  export declare const tsLibVersion = "^2.3.0";
4
- export declare const coreJsVersion = "^3.36.1";
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.coreJsVersion = exports.tsLibVersion = exports.swcLoaderVersion = exports.nxVersion = void 0;
3
+ exports.tsLibVersion = exports.swcLoaderVersion = exports.rollupVersion = exports.coreJsVersion = exports.nxVersion = void 0;
4
4
  exports.nxVersion = require('../../package.json').version;
5
+ exports.coreJsVersion = '^3.36.1';
6
+ exports.rollupVersion = '^4.14.0';
5
7
  exports.swcLoaderVersion = '0.1.15';
6
8
  exports.tsLibVersion = '^2.3.0';
7
- exports.coreJsVersion = '^3.36.1';
package/with-nx.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { withNx } from './src/plugins/with-nx/with-nx';
2
+ export type { RollupWithNxPluginOptions } from './src/plugins/with-nx/with-nx-options';
package/with-nx.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withNx = void 0;
4
+ var with_nx_1 = require("./src/plugins/with-nx/with-nx");
5
+ Object.defineProperty(exports, "withNx", { enumerable: true, get: function () { return with_nx_1.withNx; } });
@@ -1,3 +0,0 @@
1
- import { PackageJson } from 'nx/src/utils/package-json';
2
- import { NormalizedRollupExecutorOptions } from './normalize';
3
- export declare function updatePackageJson(options: NormalizedRollupExecutorOptions, packageJson: PackageJson): void;