/** Creates a rollup bundle of a specified JavaScript file.*/ private async createRollupBundle(config: RollupBundleConfig) { const bundleOptions = { context: 'this', external: Object.keys(rollupGlobals), input: config.entry, onwarn: (message: string) => { // TODO(jelbourn): figure out *why* rollup warns about certain symbols not being found // when those symbols don't appear to be in the input file in the first place. if (/but never used/.test(message)) { return false; } console.warn(message); }, plugins: [ rollupRemoveLicensesPlugin, ] }; const writeOptions = { name: config.moduleName || 'ng.flexLayout', amd: {id: config.importName}, banner: buildConfig.licenseBanner, format: config.format, file: config.dest, globals: rollupGlobals, sourcemap: true }; // For UMD bundles, we need to adjust the `external` bundle option in order to include // all necessary code in the bundle. if (config.format === 'umd') { bundleOptions.plugins.push(rollupNodeResolutionPlugin()); // For all UMD bundles, we want to exclude tslib from the `external` bundle option so that // it is inlined into the bundle. let external = Object.keys(rollupGlobals); external.splice(external.indexOf('tslib'), 1); // If each secondary entry-point is re-exported at the root, we want to exlclude those // secondary entry-points from the rollup globals because we want the UMD for this package // to include *all* of the sources for those entry-points. if (this.buildPackage.exportsSecondaryEntryPointsAtRoot && config.moduleName === `ng.${this.buildPackage.name}`) { const importRegex = new RegExp(`@angular/${this.buildPackage.name}/.+`); external = external.filter(e => !importRegex.test(e)); // Use the rollup-alias plugin to map imports of the form `@angular/material/button` // to the actual file location so that rollup can resolve the imports (otherwise they // will be treated as external dependencies and not included in the bundle). bundleOptions.plugins.push( rollupAlias(this.getResolvedSecondaryEntryPointImportPaths(config.dest))); } bundleOptions.external = external; } return rollup.rollup(bundleOptions).then((bundle: any) => bundle.write(writeOptions)); }
export function createRollupBundle(config: BundleConfig): Promise<any> { const bundleOptions: any = { context: 'this', external: config.external, entry: config.entry, }; const writeOptions = { // Keep the moduleId empty because we don't want to force developers to a specific moduleId. moduleId: '', moduleName: config.moduleName, // banner: buildConfig.licenseBanner, format: config.format, dest: config.dest, globals: config.globals, sourceMap: true }; // When creating a UMD, we want to exclude tslib from the `external` bundle option so that it // is inlined into the bundle. if (config.format === 'umd') { bundleOptions.plugins = [resolve()]; if (bundleOptions.external && bundleOptions.external.indexOf('tslib') > -1) { bundleOptions.external.splice(bundleOptions.external.indexOf('tslib'), 1); } } return rollup.rollup(bundleOptions).then((bundle: any) => bundle.write(writeOptions)); }
export default function loadConfigFile( configFile: string, commandOptions: any = {} ): Promise<InputOptions[]> { const silent = commandOptions.silent || false; const warnings = batchWarnings(); return rollup .rollup({ input: configFile, external: (id: string) => { return (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json'; }, onwarn: warnings.add }) .then((bundle: RollupSingleFileBuild) => { if (!silent && warnings.count > 0) { stderr(tc.bold(`loaded ${relativeId(configFile)} with warnings`)); warnings.flush(); } return bundle.generate({ format: 'cjs' }); }) .then(({ code }: { code: string }) => { // temporarily override require const defaultLoader = require.extensions['.js']; require.extensions['.js'] = (module: NodeModuleWithCompile, filename: string) => { if (filename === configFile) { module._compile(code, filename); } else { defaultLoader(module, filename); } }; delete require.cache[configFile]; return Promise.resolve(require(configFile)) .then(configFileContent => { if (typeof configFileContent === 'function') { return configFileContent(commandOptions); } return configFileContent; }) .then(configs => { if (Object.keys(configs).length === 0) { handleError({ code: 'MISSING_CONFIG', message: 'Config file must export an options object, or an array of options objects', url: 'https://rollupjs.org/guide/en#configuration-files' }); } require.extensions['.js'] = defaultLoader; return Array.isArray(configs) ? configs : [configs]; }); }); }
private static compileGlobals(cachePath: string, tree: PageTree) { const pageCachePath = join(cachePath, tree.context.$PAGE.$name); return rollup.rollup({ entry: tree.scripts.globals.map(x => x.path), context: "window", plugins: [ includes({ paths: [ join(pageCachePath, "scripts")] }), multientry({ exports: false }), nodeResolve({ jsnext: true }), commonjs({}), babel({ presets: [ [ "es2015", { "modules": false } ] ], "plugins": [ "external-helpers" ], exclude: "node_modules/**" }) ] }).then(bundle => bundle.generate({format: "iife", exports: "none", sourceMap: true}).code); }
async function generateToolsJs(): Promise<void> { for (const bin of ["configure-ui", "dump-data-model"]) { const inputFile = path.resolve(INPUT_DIR, `tools/${bin}`); const outputFile = path.resolve(OUTPUT_DIR, `tools/${bin}`); const bundle = await rollup({ input: inputFile, external: externals, acorn: { allowHashBang: true }, plugins: [ rollupReplace({ delimiters: ["", ""], "#!/usr/bin/env -S node -r esm -r ts-node/register/transpile-only": "" }), typescript({ tsconfig: "./tsconfig.json", include: [`tools/${bin}`, "lib/**/*.ts"] }), MODE === "production" ? terser() : null ] }); await bundle.write({ format: "cjs", preferConst: true, banner: "#!/usr/bin/env node", file: outputFile }); // Mark as executable const mode = fs.statSync(outputFile).mode; fs.chmodSync(outputFile, mode | 73); } }
export function createRollupBundle(config: BundleConfig): Promise<any> { const bundleOptions: any = { context: 'this', external: Object.keys(ROLLUP_GLOBALS), entry: config.entry, }; const writeOptions = { // Keep the moduleId empty because we don't want to force developers to a specific moduleId. moduleId: '', moduleName: config.moduleName || 'ng.material', banner: LICENSE_BANNER, format: config.format, dest: config.dest, globals: ROLLUP_GLOBALS, sourceMap: true }; // When creating a UMD, we want to exclude tslib from the `external` bundle option so that it // is inlined into the bundle. if (config.format === 'umd') { bundleOptions.plugins = [rollupNodeResolutionPlugin()]; const external = Object.keys(ROLLUP_GLOBALS); external.splice(external.indexOf('tslib'), 1); bundleOptions.external = external; } return rollup.rollup(bundleOptions).then((bundle: any) => bundle.write(writeOptions)); }
export = (done: any) => { rollup .rollup(config) .then((bundle: any) => bundle.generate({ format: 'iife', sourcemap: Config.PRESERVE_SOURCE_MAPS }) ) .then((result: any) => { const path = join(Config.TMP_DIR, 'bundle.js'); parallel(getTasks(path, result), (error: any, results: boolean[]) => { if (error && results.indexOf(false) === -1) { console.error(error); process.exit(0); } done(); }); }) .catch((error: any) => { console.error(error); process.exit(0); }); };
return new Promise((resolve, reject) => { let rollupConfig = getRollupConfig(context, configFile); rollupConfig.dest = getOutputDest(context, rollupConfig); // replace any path vars like {{TMP}} with the real path rollupConfig.entry = replacePathVars(context, normalize(rollupConfig.entry)); rollupConfig.dest = replacePathVars(context, normalize(rollupConfig.dest)); addRollupPluginIfNecessary(context, rollupConfig.plugins); // tell rollup to use a previous bundle as its starting point rollupConfig.cache = cachedBundle; if (!rollupConfig.onwarn) { // use our own logger if one wasn't already provided rollupConfig.onwarn = createOnWarnFn(); } Logger.debug(`entry: ${rollupConfig.entry}, dest: ${rollupConfig.dest}, cache: ${rollupConfig.cache}, format: ${rollupConfig.format}`); // bundle the app then create create css rollupBundler.rollup(rollupConfig) .then((bundle: RollupBundle) => { Logger.debug(`bundle.modules: ${bundle.modules.length}`); // set the module files used in this bundle // this reference can be used elsewhere in the build (sass) context.moduleFiles = bundle.modules.map((m) => { // sometimes, Rollup appends weird prefixes to the path like commonjs:proxy const index = m.id.indexOf(sep); if (index >= 0) { return m.id.substring(index); } return m.id; }); // cache our bundle for later use if (context.isWatch) { cachedBundle = bundle; } // write the bundle return bundle.write(rollupConfig); }) .then(() => { // clean up any references (overkill yes, but let's play it safe) rollupConfig = rollupConfig.cache = rollupConfig.onwarn = rollupConfig.plugins = null; resolve(); }) .catch((err: any) => { // ensure references are cleared up when there's an error cachedBundle = rollupConfig = rollupConfig.cache = rollupConfig.onwarn = rollupConfig.plugins = null; reject(new BuildError(err)); }); });
task(':build:components:rollup', [':build:components:inline'], () => { const globals: { [name: string]: string } = { // Angular dependencies '@angular/core': 'ng.core', '@angular/common': 'ng.common', '@angular/forms': 'ng.forms', '@angular/http': 'ng.http', '@angular/platform-browser': 'ng.platformBrowser', '@angular/platform-browser-dynamic': 'ng.platformBrowserDynamic', '@angular/material': 'ng.material', // Rxjs dependencies 'rxjs/Observable': 'Rx', 'rxjs/Subject': 'Rx', 'rxjs/BehaviorSubject': 'Rx', 'rxjs/scheduler/queue': 'Rx', 'rxjs/add/observable/from': 'Rx.Observable', 'rxjs/add/observable/of': 'Rx.Observable', 'rxjs/add/operator/distinctUntilChanged': 'Rx.Observable.prototype', 'rxjs/add/operator/filter': 'Rx.Observable.prototype', 'rxjs/add/operator/let': 'Rx.Observable.prototype', 'rxjs/add/operator/map': 'Rx.Observable.prototype', 'rxjs/add/operator/mergeMap': 'Rx.Observable.prototype', 'rxjs/add/operator/observeOn': 'Rx.Observable.prototype', 'rxjs/add/operator/pluck': 'Rx.Observable.prototype', 'rxjs/add/operator/scan': 'Rx.Observable.prototype', 'rxjs/add/operator/skip': 'Rx.Observable.prototype', 'rxjs/add/operator/take': 'Rx.Observable.prototype', 'rxjs/add/operator/takeUntil': 'Rx.Observable.prototype', 'rxjs/add/operator/withLatestFrom': 'Rx.Observable.prototype', }; // Rollup the UMD bundle from all ES5 + imports JavaScript files built. return rollup({ entry: path.join(DIST_COMPONENTS_ROOT, 'index.js'), context: 'this', external: Object.keys(globals) }).then((bundle: { generate: any }) => { const result = bundle.generate({ moduleName: 'ng2-md-datatable', format: 'umd', globals, sourceMap: true, dest: path.join(DIST_COMPONENTS_ROOT, 'ng2-md-datatable.umd.js') }); // Add source map URL to the code. result.code += '\n\n//# sourceMappingURL=./ng2-md-datatable.umd.js.map\n'; // Format mapping to show properly in the browser. Rollup by default will put the path // as relative to the file, and since that path is in src/lib and the file is in // dist/@angular/material, we need to kill a few `../`. result.map.sources = result.map.sources.map((s: string) => s.replace(/^(\.\.\/)+/, '')); writeFileSync(path.join(DIST_COMPONENTS_ROOT, 'ng2-md-datatable.umd.js'), result.code, 'utf8'); writeFileSync(path.join(DIST_COMPONENTS_ROOT, 'ng2-md-datatable.umd.js.map'), result.map, 'utf8'); }); });
async function generateBackendJs(): Promise<void> { for (const bin of [ "genieacs-cwmp", "genieacs-ext", "genieacs-nbi", "genieacs-fs", "genieacs-ui" ]) { const inputFile = path.resolve(INPUT_DIR, `bin/${bin}`); const outputFile = path.resolve(OUTPUT_DIR, `bin/${bin}`); const bundle = await rollup({ input: inputFile, external: externals, acorn: { allowHashBang: true }, treeshake: { propertyReadSideEffects: false, pureExternalModules: true }, plugins: [ rollupReplace({ delimiters: ["", ""], "#!/usr/bin/env -S node -r esm -r ts-node/register/transpile-only": "" }), rollupJson({ preferConst: true }), { resolveId: (importee, importer) => { if (importee.endsWith("/package.json")) { const p = path.resolve(path.dirname(importer), importee); if (p === path.resolve(INPUT_DIR, "package.json")) return path.resolve(OUTPUT_DIR, "package.json"); } return null; } }, typescript({ tsconfig: "./tsconfig.json", include: [`bin/${bin}`, "lib/**/*.ts"] }), MODE === "production" ? terser() : null ] }); await bundle.write({ format: "cjs", preferConst: true, banner: "#!/usr/bin/env node", file: outputFile }); // Mark as executable const mode = fs.statSync(outputFile).mode; fs.chmodSync(outputFile, mode | 73); } }