UNPKG

6.51 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3/*
4 * Copyright 2014-2019 Guy Bedford (http://guybedford.com)
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18const rollup = require("rollup");
19const jspmRollup = require("rollup-plugin-jspm");
20const terserPlugin = require("rollup-plugin-terser");
21const rimraf = require("rimraf");
22const mkdirp = require("mkdirp");
23const common_1 = require("../utils/common");
24const path = require("path");
25const ui_1 = require("../utils/ui");
26const resolve_1 = require("@jspm/resolve");
27const process = require("process");
28async function build(input, opts) {
29 // esm / cjs as internal default while not yet widely used in Rollup ecosystem
30 if (!opts.format)
31 opts.format = 'esm';
32 if (opts.format === 'module')
33 opts.format = 'esm';
34 if (opts.format === 'commonjs')
35 opts.format = 'cjs';
36 let ext = opts.mjs ? '.mjs' : '.js';
37 if (opts.dir && opts.dir.endsWith('/'))
38 opts.dir = opts.dir.slice(0, -1);
39 const isRecord = (x) => {
40 return Array.isArray(x) === false;
41 };
42 let inputObj;
43 if (isRecord(input)) {
44 inputObj = input;
45 }
46 else {
47 if (input.length === 0) {
48 ui_1.warn(`No inputs provided to build.`);
49 return;
50 }
51 inputObj = {};
52 for (const module of input) {
53 if (opts.format === 'esm' && 'mjs' in opts === false && module.endsWith('.mjs'))
54 ext = '.mjs';
55 let basename = path.basename(module);
56 if (basename.indexOf('.') !== -1)
57 basename = basename.substr(0, basename.lastIndexOf('.'));
58 let inputName = basename;
59 let i = 0;
60 while (inputName in inputObj)
61 inputName = basename + i++;
62 inputObj[inputName] = module;
63 }
64 }
65 // use .mjs if the output package boundary requires
66 if (opts.format === 'esm' && 'mjs' in opts === false && ext !== '.mjs') {
67 const outdir = path.resolve(opts.dir);
68 const boundary = resolve_1.utils.getPackageBoundarySync.call(resolve_1.fs, outdir + '/');
69 if (boundary) {
70 const pjson = resolve_1.utils.readPackageConfigSync.call(resolve_1.fs, boundary);
71 if (pjson.type !== 'module') {
72 let pjsonPath = path.relative(process.cwd(), boundary + '/package.json');
73 if (!pjsonPath.startsWith('..' + path.sep))
74 pjsonPath = '.' + path.sep + pjsonPath;
75 ui_1.warn(`Output package scope at ${common_1.highlight(pjsonPath)} does not have a ${common_1.bold('"type": "module"')} boundary, so outputting mjs.`);
76 ext = '.mjs';
77 }
78 }
79 }
80 const rollupOptions = {
81 input: inputObj,
82 dir: opts.dir,
83 onwarn: () => { },
84 sourcemap: opts.sourceMap,
85 plugins: [jspmRollup({
86 projectPath: opts.projectPath || process.cwd(),
87 externals: opts.external,
88 env: opts.env
89 })]
90 };
91 if (opts.minify) {
92 rollupOptions.plugins.push(terserPlugin.terser({
93 sourcemap: opts.sourceMap
94 }));
95 }
96 if (opts.watch) {
97 rollupOptions.output = {
98 dir: opts.dir,
99 format: opts.format,
100 sourcemap: opts.sourceMap,
101 indent: true,
102 banner: opts.banner
103 };
104 const watcher = await rollup.watch(rollupOptions);
105 let firstRun = true;
106 watcher.on('event', event => {
107 if (firstRun)
108 firstRun = false;
109 else if (event.code === 'BUNDLE_START')
110 ui_1.info(`Rebuilding...`);
111 else if (event.code === 'BUNDLE_END')
112 ui_1.ok(`Built into ${common_1.bold(opts.dir)}`);
113 });
114 // pause indefinitely
115 await new Promise((_resolve, _reject) => { });
116 }
117 const build = await rollup.rollup(rollupOptions);
118 if (opts.clearDir) {
119 rimraf.sync(opts.dir);
120 mkdirp.sync(opts.dir);
121 }
122 const { output } = await build.write({
123 entryFileNames: '[name]' + (opts.hashEntries ? '-[hash]' : '') + ext,
124 chunkFileNames: 'chunk-[hash]' + ext,
125 dir: opts.dir,
126 format: opts.format,
127 sourcemap: opts.sourceMap,
128 indent: true,
129 banner: opts.banner
130 });
131 if (opts.log)
132 ui_1.ok(`Built into ${common_1.highlight(opts.dir + '/')}`);
133 if (opts.showGraph && opts.log) {
134 console.log('');
135 // Improvements to this welcome! sizes in KB? Actual graph display? See also index.ts in es-module-optimizer
136 for (const chunk of output) {
137 const entry = chunk;
138 const deps = entry.imports;
139 console.log(`${common_1.bold(entry.name)}${deps.length ? ' imports ' : ''}${deps.sort().join(', ')}:`);
140 const modules = Object.keys(entry.modules).sort((m1, m2) => m1 > m2 ? 1 : -1);
141 for (let module of modules) {
142 console.log(` ${path.relative(process.cwd(), module).replace(common_1.winSepRegEx, '/')}`);
143 }
144 console.log('');
145 }
146 }
147 const imports = Object.create(null);
148 const mapBase = opts.mapBase || process.cwd();
149 // Make sure the rollup output array is in the same order as input array
150 const inputObjKeys = Object.keys(inputObj);
151 const filteredOutput = output.filter(out => out.isEntry);
152 filteredOutput.sort((a, b) => inputObjKeys.indexOf(a.name) - inputObjKeys.indexOf(b.name));
153 for (const [index, key] of inputObjKeys.entries()) {
154 const resolvedFile = path.resolve(opts.dir, filteredOutput[index].fileName);
155 let relMap = path.relative(mapBase, resolvedFile).replace(/\\/g, '/');
156 if (!relMap.startsWith('../'))
157 relMap = './' + relMap;
158 imports[inputObj[key]] = relMap;
159 }
160 return { imports };
161}
162exports.build = build;
163//# sourceMappingURL=index.js.map
\No newline at end of file