@nx/rollup 0.0.0-pr-22179-271588f

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 (48) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +68 -0
  3. package/executors.json +9 -0
  4. package/generators.json +19 -0
  5. package/index.d.ts +7 -0
  6. package/index.js +11 -0
  7. package/migrations.json +29 -0
  8. package/package.json +64 -0
  9. package/plugin.d.ts +1 -0
  10. package/plugin.js +5 -0
  11. package/src/executors/rollup/lib/analyze-plugin.d.ts +4 -0
  12. package/src/executors/rollup/lib/analyze-plugin.js +25 -0
  13. package/src/executors/rollup/lib/normalize.d.ts +11 -0
  14. package/src/executors/rollup/lib/normalize.js +86 -0
  15. package/src/executors/rollup/lib/run-rollup.d.ts +4 -0
  16. package/src/executors/rollup/lib/run-rollup.js +15 -0
  17. package/src/executors/rollup/lib/swc-plugin.d.ts +2 -0
  18. package/src/executors/rollup/lib/swc-plugin.js +20 -0
  19. package/src/executors/rollup/lib/update-package-json.d.ts +3 -0
  20. package/src/executors/rollup/lib/update-package-json.js +93 -0
  21. package/src/executors/rollup/rollup.impl.d.ts +13 -0
  22. package/src/executors/rollup/rollup.impl.js +288 -0
  23. package/src/executors/rollup/schema.d.ts +36 -0
  24. package/src/executors/rollup/schema.json +182 -0
  25. package/src/generators/configuration/configuration.d.ts +4 -0
  26. package/src/generators/configuration/configuration.js +94 -0
  27. package/src/generators/configuration/schema.d.ts +14 -0
  28. package/src/generators/configuration/schema.json +86 -0
  29. package/src/generators/init/init.d.ts +4 -0
  30. package/src/generators/init/init.js +44 -0
  31. package/src/generators/init/schema.d.ts +7 -0
  32. package/src/generators/init/schema.json +33 -0
  33. package/src/migrations/update-15-0-0/add-babel-inputs.d.ts +2 -0
  34. package/src/migrations/update-15-0-0/add-babel-inputs.js +9 -0
  35. package/src/migrations/update-16-0-0-add-nx-packages/update-16-0-0-add-nx-packages.d.ts +2 -0
  36. package/src/migrations/update-16-0-0-add-nx-packages/update-16-0-0-add-nx-packages.js +9 -0
  37. package/src/migrations/update-16-3-3-add-babel-upward-root-mode-flag/update-16-3-3-add-babel-upward-root-mode-flag.d.ts +2 -0
  38. package/src/migrations/update-16-3-3-add-babel-upward-root-mode-flag/update-16-3-3-add-babel-upward-root-mode-flag.js +17 -0
  39. package/src/migrations/update-16-6-0/explicitly-set-projects-to-update-buildable-deps.d.ts +2 -0
  40. package/src/migrations/update-16-6-0/explicitly-set-projects-to-update-buildable-deps.js +29 -0
  41. package/src/plugins/plugin.d.ts +6 -0
  42. package/src/plugins/plugin.js +104 -0
  43. package/src/utils/ensure-dependencies.d.ts +5 -0
  44. package/src/utils/ensure-dependencies.js +17 -0
  45. package/src/utils/fs.d.ts +4 -0
  46. package/src/utils/fs.js +16 -0
  47. package/src/utils/versions.d.ts +3 -0
  48. package/src/utils/versions.js +6 -0
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRollupOptions = exports.rollupExecutor = void 0;
4
+ const ts = require("typescript");
5
+ const rollup = require("rollup");
6
+ const peerDepsExternal = require("rollup-plugin-peer-deps-external");
7
+ const plugin_babel_1 = require("@rollup/plugin-babel");
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
+ const autoprefixer = require("autoprefixer");
13
+ const devkit_1 = require("@nx/devkit");
14
+ const buildable_libs_utils_1 = require("@nx/js/src/utils/buildable-libs-utils");
15
+ const plugin_node_resolve_1 = require("@rollup/plugin-node-resolve");
16
+ const type_definitions_1 = require("@nx/js/src/plugins/rollup/type-definitions");
17
+ const run_rollup_1 = require("./lib/run-rollup");
18
+ const normalize_1 = require("./lib/normalize");
19
+ const analyze_plugin_1 = require("./lib/analyze-plugin");
20
+ const fs_1 = require("../../utils/fs");
21
+ const swc_plugin_1 = require("./lib/swc-plugin");
22
+ const update_package_json_1 = require("./lib/update-package-json");
23
+ const config_utils_1 = require("@nx/devkit/src/utils/config-utils");
24
+ // These use require because the ES import isn't correct.
25
+ const commonjs = require('@rollup/plugin-commonjs');
26
+ const image = require('@rollup/plugin-image');
27
+ const json = require('@rollup/plugin-json');
28
+ const copy = require('rollup-plugin-copy');
29
+ const postcss = require('rollup-plugin-postcss');
30
+ const fileExtensions = ['.js', '.jsx', '.ts', '.tsx'];
31
+ async function* rollupExecutor(rawOptions, context) {
32
+ process.env.NODE_ENV ??= 'production';
33
+ const project = context.projectsConfigurations.projects[context.projectName];
34
+ const sourceRoot = project.sourceRoot;
35
+ const { target, dependencies } = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(context.taskGraph, context.projectGraph, context.root, context.projectName, context.targetName, context.configurationName, true);
36
+ const options = (0, normalize_1.normalizeRollupExecutorOptions)(rawOptions, context, sourceRoot);
37
+ const packageJson = (0, devkit_1.readJsonFile)(options.project);
38
+ const npmDeps = (context.projectGraph.dependencies[context.projectName] ?? [])
39
+ .filter((d) => d.target.startsWith('npm:'))
40
+ .map((d) => d.target.slice(4));
41
+ const rollupOptions = await createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps);
42
+ const outfile = resolveOutfile(context, options);
43
+ if (options.watch) {
44
+ const watcher = rollup.watch(rollupOptions);
45
+ return yield* (0, rxjs_for_await_1.eachValueFrom)(new rxjs_1.Observable((obs) => {
46
+ watcher.on('event', (data) => {
47
+ if (data.code === 'START') {
48
+ devkit_1.logger.info(`Bundling ${context.projectName}...`);
49
+ }
50
+ else if (data.code === 'END') {
51
+ (0, update_package_json_1.updatePackageJson)(options, packageJson);
52
+ devkit_1.logger.info('Bundle complete. Watching for file changes...');
53
+ obs.next({ success: true, outfile });
54
+ }
55
+ else if (data.code === 'ERROR') {
56
+ devkit_1.logger.error(`Error during bundle: ${data.error.message}`);
57
+ obs.next({ success: false });
58
+ }
59
+ });
60
+ // Teardown logic. Close watcher when unsubscribed.
61
+ return () => watcher.close();
62
+ }));
63
+ }
64
+ else {
65
+ devkit_1.logger.info(`Bundling ${context.projectName}...`);
66
+ // Delete output path before bundling
67
+ if (options.deleteOutputPath) {
68
+ (0, fs_1.deleteOutputDir)(context.root, options.outputPath);
69
+ }
70
+ const start = process.hrtime.bigint();
71
+ return (0, rxjs_1.from)(rollupOptions)
72
+ .pipe((0, operators_1.concatMap)((opts) => (0, run_rollup_1.runRollup)(opts).pipe((0, operators_1.catchError)((e) => {
73
+ devkit_1.logger.error(`Error during bundle: ${e}`);
74
+ return (0, rxjs_1.of)({ success: false });
75
+ }))), (0, operators_1.scan)((acc, result) => {
76
+ if (!acc.success)
77
+ return acc;
78
+ return result;
79
+ }, { success: true, outfile }), (0, operators_1.last)(), (0, operators_1.tap)({
80
+ next: (result) => {
81
+ if (result.success) {
82
+ const end = process.hrtime.bigint();
83
+ const duration = `${(Number(end - start) / 1000000000).toFixed(2)}s`;
84
+ (0, update_package_json_1.updatePackageJson)(options, packageJson);
85
+ devkit_1.logger.info(`⚡ Done in ${duration}`);
86
+ }
87
+ else {
88
+ devkit_1.logger.error(`Bundle failed: ${context.projectName}`);
89
+ }
90
+ },
91
+ }))
92
+ .toPromise();
93
+ }
94
+ }
95
+ exports.rollupExecutor = rollupExecutor;
96
+ // -----------------------------------------------------------------------------
97
+ async function createRollupOptions(options, dependencies, context, packageJson, sourceRoot, npmDeps) {
98
+ const useBabel = options.compiler === 'babel';
99
+ const useTsc = options.compiler === 'tsc';
100
+ const useSwc = options.compiler === 'swc';
101
+ const tsConfigPath = (0, devkit_1.joinPathFragments)(context.root, options.tsConfig);
102
+ const configFile = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
103
+ const config = ts.parseJsonConfigFileContent(configFile.config, ts.sys, (0, path_1.dirname)(tsConfigPath));
104
+ if (!options.format || !options.format.length) {
105
+ options.format = readCompatibleFormats(config);
106
+ }
107
+ if (packageJson.type === 'module') {
108
+ if (options.format.includes('cjs')) {
109
+ 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.`);
110
+ }
111
+ options.format = ['esm'];
112
+ }
113
+ else if (packageJson.type === 'commonjs') {
114
+ if (options.format.includes('esm')) {
115
+ 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.`);
116
+ }
117
+ options.format = ['cjs'];
118
+ }
119
+ const _rollupOptions = options.format.map(async (format, idx) => {
120
+ // Either we're generating only one format, so we should bundle types
121
+ // OR we are generating dual formats, so only bundle types for CJS.
122
+ const shouldBundleTypes = options.format.length === 1 || format === 'cjs';
123
+ const plugins = [
124
+ copy({
125
+ targets: convertCopyAssetsToRollupOptions(options.outputPath, options.assets),
126
+ }),
127
+ image(),
128
+ json(),
129
+ (useTsc || shouldBundleTypes) &&
130
+ require('rollup-plugin-typescript2')({
131
+ check: !options.skipTypeCheck,
132
+ tsconfig: options.tsConfig,
133
+ tsconfigOverride: {
134
+ compilerOptions: createTsCompilerOptions(config, dependencies, options),
135
+ },
136
+ }),
137
+ shouldBundleTypes &&
138
+ (0, type_definitions_1.typeDefinitions)({
139
+ main: options.main,
140
+ projectRoot: options.projectRoot,
141
+ }),
142
+ peerDepsExternal({
143
+ packageJsonPath: options.project,
144
+ }),
145
+ postcss({
146
+ inject: true,
147
+ extract: options.extractCss,
148
+ autoModules: true,
149
+ plugins: [autoprefixer],
150
+ use: {
151
+ less: {
152
+ javascriptEnabled: options.javascriptEnabled,
153
+ },
154
+ },
155
+ }),
156
+ (0, plugin_node_resolve_1.default)({
157
+ preferBuiltins: true,
158
+ extensions: fileExtensions,
159
+ }),
160
+ useSwc && (0, swc_plugin_1.swc)(),
161
+ useBabel &&
162
+ (0, plugin_babel_1.getBabelInputPlugin)({
163
+ // Lets `@nx/js/babel` preset know that we are packaging.
164
+ caller: {
165
+ // @ts-ignore
166
+ // Ignoring type checks for caller since we have custom attributes
167
+ isNxPackage: true,
168
+ // Always target esnext and let rollup handle cjs
169
+ supportsStaticESM: true,
170
+ isModern: true,
171
+ },
172
+ cwd: (0, path_1.join)(context.root, sourceRoot),
173
+ rootMode: options.babelUpwardRootMode ? 'upward' : undefined,
174
+ babelrc: true,
175
+ extensions: fileExtensions,
176
+ babelHelpers: 'bundled',
177
+ skipPreflightCheck: true, // pre-flight check may yield false positives and also slows down the build
178
+ exclude: /node_modules/,
179
+ plugins: [
180
+ format === 'esm'
181
+ ? undefined
182
+ : require.resolve('babel-plugin-transform-async-to-promises'),
183
+ ].filter(Boolean),
184
+ }),
185
+ commonjs(),
186
+ (0, analyze_plugin_1.analyze)(),
187
+ ];
188
+ let externalPackages = [
189
+ ...Object.keys(packageJson.dependencies || {}),
190
+ ...Object.keys(packageJson.peerDependencies || {}),
191
+ ]; // If external is set to none, include all dependencies and peerDependencies in externalPackages
192
+ if (options.external === 'all') {
193
+ externalPackages = externalPackages
194
+ .concat(dependencies.map((d) => d.name))
195
+ .concat(npmDeps);
196
+ }
197
+ else if (Array.isArray(options.external) && options.external.length > 0) {
198
+ externalPackages = externalPackages.concat(options.external);
199
+ }
200
+ externalPackages = [...new Set(externalPackages)];
201
+ const mainEntryFileName = options.outputFileName || options.main;
202
+ const input = {};
203
+ input[(0, path_1.parse)(mainEntryFileName).name] = options.main;
204
+ options.additionalEntryPoints.forEach((entry) => {
205
+ input[(0, path_1.parse)(entry).name] = entry;
206
+ });
207
+ const rollupConfig = {
208
+ input,
209
+ output: {
210
+ format,
211
+ dir: `${options.outputPath}`,
212
+ name: (0, devkit_1.names)(context.projectName).className,
213
+ entryFileNames: `[name].${format}.js`,
214
+ chunkFileNames: `[name].${format}.js`,
215
+ },
216
+ external: (id) => {
217
+ return externalPackages.some((name) => id === name || id.startsWith(`${name}/`)); // Could be a deep import
218
+ },
219
+ plugins,
220
+ };
221
+ const userDefinedRollupConfigs = options.rollupConfig.map((plugin) => (0, config_utils_1.loadConfigFile)(plugin));
222
+ let finalConfig = rollupConfig;
223
+ for (const _config of userDefinedRollupConfigs) {
224
+ const config = await _config;
225
+ if (typeof config === 'function') {
226
+ finalConfig = config(finalConfig, options);
227
+ }
228
+ else {
229
+ finalConfig = {
230
+ ...finalConfig,
231
+ ...config,
232
+ plugins: [
233
+ ...(finalConfig.plugins?.length > 0 ? finalConfig.plugins : []),
234
+ ...(config.plugins?.length > 0 ? config.plugins : []),
235
+ ],
236
+ };
237
+ }
238
+ }
239
+ return finalConfig;
240
+ });
241
+ const rollupOptions = [];
242
+ for (const rollupOption of _rollupOptions) {
243
+ rollupOptions.push(await rollupOption);
244
+ }
245
+ return rollupOptions;
246
+ }
247
+ exports.createRollupOptions = createRollupOptions;
248
+ function createTsCompilerOptions(config, dependencies, options) {
249
+ const compilerOptionPaths = (0, buildable_libs_utils_1.computeCompilerOptionsPaths)(config, dependencies);
250
+ const compilerOptions = {
251
+ rootDir: options.projectRoot,
252
+ allowJs: options.allowJs,
253
+ declaration: true,
254
+ paths: compilerOptionPaths,
255
+ };
256
+ if (config.options.module === ts.ModuleKind.CommonJS) {
257
+ compilerOptions['module'] = 'ESNext';
258
+ }
259
+ if (options.compiler === 'swc') {
260
+ compilerOptions['emitDeclarationOnly'] = true;
261
+ }
262
+ return compilerOptions;
263
+ }
264
+ function convertCopyAssetsToRollupOptions(outputPath, assets) {
265
+ return assets
266
+ ? assets.map((a) => ({
267
+ src: (0, path_1.join)(a.input, a.glob).replace(/\\/g, '/'),
268
+ dest: (0, path_1.join)(outputPath, a.output).replace(/\\/g, '/'),
269
+ }))
270
+ : undefined;
271
+ }
272
+ function readCompatibleFormats(config) {
273
+ switch (config.options.module) {
274
+ case ts.ModuleKind.CommonJS:
275
+ case ts.ModuleKind.UMD:
276
+ case ts.ModuleKind.AMD:
277
+ return ['cjs'];
278
+ default:
279
+ return ['esm'];
280
+ }
281
+ }
282
+ function resolveOutfile(context, options) {
283
+ if (!options.format?.includes('cjs'))
284
+ return undefined;
285
+ const { name } = (0, path_1.parse)(options.outputFileName ?? options.main);
286
+ return (0, path_1.resolve)(context.root, options.outputPath, `${name}.cjs.js`);
287
+ }
288
+ exports.default = rollupExecutor;
@@ -0,0 +1,36 @@
1
+ type Compiler = 'babel' | 'swc';
2
+
3
+ export interface AssetGlobPattern {
4
+ glob: string;
5
+ input: string;
6
+ output: string;
7
+ ignore?: string[];
8
+ }
9
+
10
+ export interface Globals {
11
+ moduleId: string;
12
+ global: string;
13
+ }
14
+
15
+ export interface RollupExecutorOptions {
16
+ outputPath: string;
17
+ tsConfig: string;
18
+ allowJs?: boolean;
19
+ project: string;
20
+ main: string;
21
+ outputFileName?: string;
22
+ extractCss?: boolean | string;
23
+ external?: string[] | 'all' | 'none';
24
+ rollupConfig?: string | string[];
25
+ watch?: boolean;
26
+ assets?: any[];
27
+ deleteOutputPath?: boolean;
28
+ format?: ('cjs' | 'esm')[];
29
+ compiler?: 'babel' | 'tsc' | 'swc';
30
+ javascriptEnabled?: boolean;
31
+ generateExportsField?: boolean;
32
+ additionalEntryPoints?: string[];
33
+ skipTypeCheck?: boolean;
34
+ babelUpwardRootMode?: boolean;
35
+ skipTypeField?: boolean;
36
+ }
@@ -0,0 +1,182 @@
1
+ {
2
+ "version": 2,
3
+ "outputCapture": "direct-nodejs",
4
+ "title": "Web Library Rollup Target (Experimental)",
5
+ "description": "Packages a library for different web usages (ESM, CommonJS).",
6
+ "cli": "nx",
7
+ "type": "object",
8
+ "properties": {
9
+ "project": {
10
+ "type": "string",
11
+ "description": "The path to package.json file.",
12
+ "x-priority": "important"
13
+ },
14
+ "main": {
15
+ "type": "string",
16
+ "description": "The path to the entry file, relative to project.",
17
+ "alias": "entryFile",
18
+ "x-completion-type": "file",
19
+ "x-completion-glob": "**/*@(.js|.ts)",
20
+ "x-priority": "important"
21
+ },
22
+ "outputPath": {
23
+ "type": "string",
24
+ "description": "The output path of the generated files.",
25
+ "x-completion-type": "directory",
26
+ "x-priority": "important"
27
+ },
28
+ "outputFileName": {
29
+ "type": "string",
30
+ "description": "Name of the main output file. Defaults same basename as 'main' file."
31
+ },
32
+ "deleteOutputPath": {
33
+ "type": "boolean",
34
+ "description": "Delete the output path before building.",
35
+ "default": true
36
+ },
37
+ "tsConfig": {
38
+ "type": "string",
39
+ "description": "The path to tsconfig file.",
40
+ "x-completion-type": "file",
41
+ "x-completion-glob": "tsconfig.*.json",
42
+ "x-priority": "important"
43
+ },
44
+ "allowJs": {
45
+ "type": "boolean",
46
+ "description": "Allow JavaScript files to be compiled.",
47
+ "default": false
48
+ },
49
+ "format": {
50
+ "type": "array",
51
+ "description": "List of module formats to output. Defaults to matching format from tsconfig (e.g. CJS for CommonJS, and ESM otherwise).",
52
+ "alias": "f",
53
+ "items": {
54
+ "type": "string",
55
+ "enum": ["esm", "cjs"]
56
+ }
57
+ },
58
+ "external": {
59
+ "type": "array",
60
+ "description": "A list of external modules that will not be bundled (`react`, `react-dom`, etc.). Can also be set to `all` (bundle nothing) or `none` (bundle everything).",
61
+ "oneOf": [
62
+ {
63
+ "type": "string",
64
+ "enum": ["all", "none"]
65
+ },
66
+ {
67
+ "type": "array",
68
+ "items": {
69
+ "type": "string"
70
+ }
71
+ }
72
+ ]
73
+ },
74
+ "watch": {
75
+ "type": "boolean",
76
+ "description": "Enable re-building when files change.",
77
+ "default": false
78
+ },
79
+ "rollupConfig": {
80
+ "oneOf": [
81
+ {
82
+ "type": "array",
83
+ "items": {
84
+ "type": "string",
85
+ "x-completion-type": "file",
86
+ "x-completion-glob": "rollup?(*)@(.js|.ts)"
87
+ }
88
+ },
89
+ {
90
+ "type": "string",
91
+ "x-completion-type": "file",
92
+ "x-completion-glob": "rollup?(*)@(.js|.ts)"
93
+ }
94
+ ],
95
+ "description": "Path to a function which takes a rollup config and returns an updated rollup config."
96
+ },
97
+ "extractCss": {
98
+ "type": ["boolean", "string"],
99
+ "description": "CSS files will be extracted to the output folder. Alternatively custom filename can be provided (e.g. styles.css)",
100
+ "default": true
101
+ },
102
+ "assets": {
103
+ "type": "array",
104
+ "description": "List of static assets.",
105
+ "default": [],
106
+ "items": {
107
+ "$ref": "#/definitions/assetPattern"
108
+ }
109
+ },
110
+ "compiler": {
111
+ "type": "string",
112
+ "enum": ["babel", "swc", "tsc"],
113
+ "default": "babel",
114
+ "description": "Which compiler to use."
115
+ },
116
+ "babelUpwardRootMode": {
117
+ "type": "boolean",
118
+ "description": "Whether to set rootmode to upward. See https://babeljs.io/docs/en/options#rootmode",
119
+ "default": false
120
+ },
121
+ "javascriptEnabled": {
122
+ "type": "boolean",
123
+ "description": "Sets `javascriptEnabled` option for less loader",
124
+ "default": false
125
+ },
126
+ "generateExportsField": {
127
+ "type": "boolean",
128
+ "alias": "exports",
129
+ "description": "Update the output package.json file's 'exports' field. This field is used by Node and bundles.",
130
+ "default": false,
131
+ "x-priority": "important"
132
+ },
133
+ "additionalEntryPoints": {
134
+ "type": "array",
135
+ "description": "Additional entry-points to add to exports field in the package.json file.",
136
+ "items": {
137
+ "type": "string"
138
+ },
139
+ "x-priority": "important"
140
+ },
141
+ "skipTypeCheck": {
142
+ "type": "boolean",
143
+ "description": "Whether to skip TypeScript type checking.",
144
+ "default": false
145
+ },
146
+ "skipTypeField": {
147
+ "type": "boolean",
148
+ "description": "Prevents 'type' field from being added to compiled package.json file. Use this if you are having an issue with this field.",
149
+ "default": false
150
+ }
151
+ },
152
+ "required": ["tsConfig", "main", "outputPath"],
153
+ "definitions": {
154
+ "assetPattern": {
155
+ "oneOf": [
156
+ {
157
+ "type": "object",
158
+ "properties": {
159
+ "glob": {
160
+ "type": "string",
161
+ "description": "The pattern to match."
162
+ },
163
+ "input": {
164
+ "type": "string",
165
+ "description": "The input directory path in which to apply `glob`. Defaults to the project root."
166
+ },
167
+ "output": {
168
+ "type": "string",
169
+ "description": "Relative path within the output folder."
170
+ }
171
+ },
172
+ "additionalProperties": false,
173
+ "required": ["glob", "input", "output"]
174
+ },
175
+ {
176
+ "type": "string"
177
+ }
178
+ ]
179
+ }
180
+ },
181
+ "examplesFile": "../../docs/rollup-examples.md"
182
+ }
@@ -0,0 +1,4 @@
1
+ import { Tree, GeneratorCallback } from '@nx/devkit';
2
+ import { RollupProjectSchema } from './schema';
3
+ export declare function configurationGenerator(tree: Tree, options: RollupProjectSchema): Promise<GeneratorCallback>;
4
+ export default configurationGenerator;
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.configurationGenerator = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const get_import_path_1 = require("@nx/js/src/utils/get-import-path");
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");
9
+ async function configurationGenerator(tree, options) {
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
+ }
15
+ options.buildTarget ??= 'build';
16
+ checkForTargetConflicts(tree, options);
17
+ addBuildTarget(tree, options);
18
+ if (!options.skipFormat) {
19
+ await (0, devkit_1.formatFiles)(tree);
20
+ }
21
+ return (0, devkit_1.runTasksInSerial)(...tasks);
22
+ }
23
+ exports.configurationGenerator = configurationGenerator;
24
+ function checkForTargetConflicts(tree, options) {
25
+ if (options.skipValidation)
26
+ return;
27
+ const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
28
+ if (project.targets?.[options.buildTarget]) {
29
+ throw new Error(`Project "${options.project}" already has a ${options.buildTarget} target. Pass --skipValidation to ignore this error.`);
30
+ }
31
+ }
32
+ function addBuildTarget(tree, options) {
33
+ (0, add_build_target_defaults_1.addBuildTargetDefaults)(tree, '@nx/rollup:rollup', options.buildTarget);
34
+ const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
35
+ const packageJsonPath = (0, devkit_1.joinPathFragments)(project.root, 'package.json');
36
+ if (!tree.exists(packageJsonPath)) {
37
+ const importPath = options.importPath || (0, get_import_path_1.getImportPath)(tree, options.project);
38
+ (0, devkit_1.writeJson)(tree, packageJsonPath, {
39
+ name: importPath,
40
+ version: '0.0.1',
41
+ });
42
+ }
43
+ const prevBuildOptions = project.targets?.[options.buildTarget]?.options;
44
+ const buildOptions = {
45
+ main: options.main ??
46
+ prevBuildOptions?.main ??
47
+ (0, devkit_1.joinPathFragments)(project.root, 'src/main.ts'),
48
+ outputPath: prevBuildOptions?.outputPath ??
49
+ (0, devkit_1.joinPathFragments)('dist', project.root === '.' ? project.name : project.root),
50
+ tsConfig: options.tsConfig ??
51
+ prevBuildOptions?.tsConfig ??
52
+ (0, devkit_1.joinPathFragments)(project.root, 'tsconfig.lib.json'),
53
+ additionalEntryPoints: prevBuildOptions?.additionalEntryPoints,
54
+ generateExportsField: prevBuildOptions?.generateExportsField,
55
+ compiler: options.compiler ?? 'babel',
56
+ project: `${project.root}/package.json`,
57
+ external: options.external,
58
+ format: options.format,
59
+ };
60
+ if (options.rollupConfig) {
61
+ buildOptions.rollupConfig = options.rollupConfig;
62
+ }
63
+ if (tree.exists((0, devkit_1.joinPathFragments)(project.root, 'README.md'))) {
64
+ buildOptions.assets = [
65
+ {
66
+ glob: `${project.root}/README.md`,
67
+ input: '.',
68
+ output: '.',
69
+ },
70
+ ];
71
+ }
72
+ (0, devkit_1.updateProjectConfiguration)(tree, options.project, {
73
+ ...project,
74
+ targets: {
75
+ ...project.targets,
76
+ [options.buildTarget]: {
77
+ executor: '@nx/rollup:rollup',
78
+ outputs: ['{options.outputPath}'],
79
+ defaultConfiguration: 'production',
80
+ options: buildOptions,
81
+ configurations: {
82
+ production: {
83
+ optimization: true,
84
+ sourceMap: false,
85
+ namedChunks: false,
86
+ extractLicenses: true,
87
+ vendorChunk: false,
88
+ },
89
+ },
90
+ },
91
+ },
92
+ });
93
+ }
94
+ exports.default = configurationGenerator;
@@ -0,0 +1,14 @@
1
+ export interface RollupProjectSchema {
2
+ project: string;
3
+ main?: string;
4
+ tsConfig?: string;
5
+ compiler?: 'babel' | 'swc' | 'tsc';
6
+ skipFormat?: boolean;
7
+ skipPackageJson?: boolean;
8
+ skipValidation?: boolean;
9
+ importPath?: string;
10
+ external?: string[];
11
+ rollupConfig?: string;
12
+ buildTarget?: string;
13
+ format?: ('cjs' | 'esm')[];
14
+ }