UNPKG

9.41 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.getWebpackConfig = getWebpackConfig;
7exports.default = build;
8Object.defineProperty(exports, "webpack", {
9 enumerable: true,
10 get: function get() {
11 return _webpack.default;
12 }
13});
14
15require("core-js/modules/es6.array.from");
16
17require("core-js/modules/es6.symbol");
18
19require("core-js/modules/web.dom.iterable");
20
21require("core-js/modules/es6.object.assign");
22
23require("core-js/modules/es6.function.name");
24
25var _path = require("path");
26
27var _fs = require("fs");
28
29var _webpack = _interopRequireWildcard(require("webpack"));
30
31var _rimraf = _interopRequireDefault(require("rimraf"));
32
33var _chalk = _interopRequireDefault(require("chalk"));
34
35var _htmlWebpackPlugin = _interopRequireDefault(require("html-webpack-plugin"));
36
37var _copyWebpackPlugin = _interopRequireDefault(require("copy-webpack-plugin"));
38
39var _swPrecacheWebpackPlugin = _interopRequireDefault(require("sw-precache-webpack-plugin"));
40
41var _uglifyjsWebpackPlugin = _interopRequireDefault(require("uglifyjs-webpack-plugin"));
42
43var _mergeCustomConfig = _interopRequireDefault(require("./merge-custom-config"));
44
45var _getWebpackCommonConfig = _interopRequireDefault(require("./get-webpack-common-config"));
46
47var _injectLoaderOptions = _interopRequireDefault(require("./inject-loader-options"));
48
49var _devServer = _interopRequireDefault(require("./dev-server"));
50
51function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
52
53function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
54
55function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
56
57function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
58
59function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
60
61function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
62
63function checkConfig(webpackConfig) {
64 var config = Array.isArray(webpackConfig) ? webpackConfig : [webpackConfig];
65 var hasEmptyEntry = config.some(function (c) {
66 return Object.keys(c.entry || {}).length === 0;
67 });
68
69 if (hasEmptyEntry) {
70 var err = new Error('no webpack entry found');
71 err.name = 'NoEntry';
72 throw err;
73 }
74}
75
76function getWebpackConfig() {
77 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
78 cwd: process.cwd()
79 };
80 var cache = arguments.length > 1 ? arguments[1] : undefined;
81 var pkgPath = (0, _path.join)(args.cwd, 'package.json');
82 var pkg = (0, _fs.existsSync)(pkgPath) ? require(pkgPath) : {};
83 var webpackConfig = (0, _getWebpackCommonConfig.default)(args);
84 (0, _injectLoaderOptions.default)(webpackConfig, args);
85 webpackConfig.plugins = webpackConfig.plugins || [];
86
87 if (args.outputPath) {
88 webpackConfig.output.path = args.outputPath;
89 }
90
91 if (args.publicPath) {
92 webpackConfig.output.publicPath = args.publicPath;
93 }
94
95 if (args.compress && !args.dev && !args.watch) {
96 webpackConfig.plugins = _toConsumableArray(webpackConfig.plugins).concat([new _uglifyjsWebpackPlugin.default({
97 parallel: true,
98 uglifyOptions: {
99 output: {
100 comments: false,
101 beautify: false,
102 ascii_only: true
103 }
104 }
105 }), new _webpack.default.DefinePlugin({
106 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
107 })]);
108 } else {
109 webpackConfig.plugins = _toConsumableArray(webpackConfig.plugins).concat([new _webpack.default.DefinePlugin({
110 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
111 })]);
112 }
113
114 webpackConfig.plugins = _toConsumableArray(webpackConfig.plugins).concat([new _webpack.default.NoEmitOnErrorsPlugin()]);
115
116 if (args.hash) {
117 webpackConfig.plugins = _toConsumableArray(webpackConfig.plugins).concat([require('map-json-webpack-plugin')({
118 assetsPath: pkg.name,
119 cache: cache
120 })]);
121 }
122
123 if (typeof args.config === 'function') {
124 webpackConfig = args.config(webpackConfig) || webpackConfig;
125 } else {
126 webpackConfig = (0, _mergeCustomConfig.default)(webpackConfig, (0, _path.resolve)(args.cwd, args.config || 'webpack.config.js'));
127 }
128
129 var commonName = args.hash ? 'js/common-[chunkhash:5].js' : 'js/common.js';
130 var entryArr = Object.keys(webpackConfig.entry);
131 entryArr.map(function (pathname) {
132 var conf = {
133 filename: "".concat(pathname, ".html"),
134 template: "".concat(webpackConfig.entry[pathname], "/page.html"),
135 inject: true,
136 chunksSortMode: 'dependency'
137 };
138
139 if (args.dev) {
140 conf.hash = true;
141 } else {
142 conf.minify = Object.assign({
143 removeComments: true,
144 collapseWhitespace: true,
145 minifyJS: true
146 }, pkg.htmlConfig || {});
147 conf.filename = "html/".concat(pathname, ".html");
148 }
149
150 if (entryArr.length > 1) {
151 conf.chunks = ['common', pathname];
152 }
153
154 webpackConfig.plugins.push(new _htmlWebpackPlugin.default(conf));
155 });
156
157 if (entryArr.length > 1) {
158 webpackConfig.plugins.push(new _webpack.default.optimize.CommonsChunkPlugin({
159 name: 'common',
160 filename: commonName
161 }));
162 }
163
164 checkConfig(webpackConfig);
165 return webpackConfig;
166}
167
168function build(args, callback) {
169 var pkgPath = (0, _path.join)(args.cwd, 'package.json');
170 var pkg = (0, _fs.existsSync)(pkgPath) ? require(pkgPath) : {};
171 var webpackConfig = getWebpackConfig(args, {});
172 webpackConfig = Array.isArray(webpackConfig) ? webpackConfig : [webpackConfig];
173 var fileOutputPath;
174 webpackConfig.forEach(function (config) {
175 fileOutputPath = config.output.path;
176
177 if (args.dev) {
178 config.plugins.push(new _webpack.default.HotModuleReplacementPlugin());
179 var devClientPath = (0, _path.resolve)(process.mainModule.filename, '../../lib/dev-client');
180 Object.keys(config.entry).forEach(function (name) {
181 config.entry[name] = [devClientPath].concat(config.entry[name]);
182 });
183 } else {
184 _rimraf.default.sync(fileOutputPath);
185
186 var _publicPath = (0, _path.resolve)(args.cwd, './public');
187
188 if ((0, _fs.existsSync)(_publicPath)) {
189 config.plugins.push(new _copyWebpackPlugin.default([{
190 from: _publicPath,
191 ignore: ['.*']
192 }], {
193 copyUnmodified: true
194 }));
195 }
196
197 if (args.pwa) {
198 config.plugins.push(new _swPrecacheWebpackPlugin.default({
199 cacheId: "".concat(pkg.name, "-res"),
200 filename: 'sw.js',
201 staticFileGlobs: ["".concat(fileOutputPath, "/**/*.{js,css,jpg,jpeg,png,gif,ico,woff,woff2,ttf,svg,eot}")],
202 minify: true,
203 navigateFallback: '/fail.html',
204 stripPrefix: "".concat(fileOutputPath)
205 }));
206 }
207 }
208 });
209 webpackConfig.forEach(function (config) {
210 config.plugins.push(new _webpack.ProgressPlugin(function (percentage, msg, addInfo) {
211 var stream = process.stderr;
212
213 if (stream.isTTY && percentage < 0.71) {
214 stream.cursorTo(0);
215 stream.write("".concat(_chalk.default.magenta(msg), " (").concat(_chalk.default.magenta(addInfo), ")"));
216 stream.clearLine(1);
217 } else if (percentage === 1) {}
218 }));
219 });
220
221 function doneHandler(err, stats) {
222 if (err) {
223 console.log(err);
224 return;
225 }
226
227 if (args.json) {
228 var filename = typeof args.json === 'boolean' ? 'build-bundle.json' : args.json;
229 var jsonPath = (0, _path.join)(fileOutputPath, filename);
230 (0, _fs.writeFileSync)(jsonPath, JSON.stringify(stats.toJson()), 'utf-8');
231 console.log("Generate Json File: ".concat(jsonPath));
232 }
233
234 var _stats$toJson = stats.toJson(),
235 errors = _stats$toJson.errors;
236
237 if (errors && errors.length) {
238 callback(errors);
239 }
240
241 if (!args.watch || stats.hasErrors()) {
242 var buildInfo = stats.toString({
243 colors: true,
244 children: true,
245 chunks: !!args.verbose,
246 modules: !!args.verbose,
247 chunkModules: !!args.verbose,
248 hash: !!args.verbose,
249 version: !!args.verbose
250 });
251
252 if (stats.hasErrors()) {
253 console.error(buildInfo);
254 } else {
255 console.log(buildInfo);
256 }
257 }
258
259 if (callback) {
260 callback(err);
261 }
262 }
263
264 var compiler = (0, _webpack.default)(webpackConfig);
265
266 if (!args.verbose) {
267 compiler.plugin('done', function (stats) {
268 stats.stats.forEach(function (stat) {
269 stat.compilation.children = stat.compilation.children.filter(function (child) {
270 return child.name !== 'extract-text-webpack-plugin';
271 });
272 });
273 });
274 }
275
276 if (args.watch) {
277 compiler.watch(args.watch || 200, doneHandler);
278 } else if (args.dev) {
279 (0, _devServer.default)(compiler, args);
280 } else {
281 compiler.run(doneHandler);
282 }
283}
\No newline at end of file