/
webpack.config.js
291 lines (249 loc) · 10.3 KB
/
webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* Copyright 2017 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* global __dirname */
'use strict';
const fs = require('fs');
const fsExtra = require('fs-extra');
const _ = require('lodash');
const path = require('path');
const upath = require('upath');
const webpack = require('webpack');
const StatsPlugin = require('stats-webpack-plugin');
const HappyPack = require('happypack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const licenseChecker = require('license-checker');
const singlePageAppModuleDir = path.join(__dirname, '..', 'webpack', 'single_page_apps');
const mithrilVersionFromNpm = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'node_modules/mithril/package.json'), 'utf8')).version;
const mithrilPatchFileContentAsLines = fs.readFileSync(path.join(__dirname, '..', 'spec/webpack/patches/mithril.js'), 'utf8').split("\n");
const isMithrilVersionLine = function (line) {
return _.includes(line, 'm.version = ');
};
const mithrilVersionFromPatch = _.find(mithrilPatchFileContentAsLines, isMithrilVersionLine)
.split("=")[1].trim().replace(/"/g, "");
if (mithrilVersionFromNpm !== mithrilVersionFromPatch) {
throw new Error("Please ensure that the patched mithril version is the same as the one installed via nodejs");
}
module.exports = function (env) {
const production = (env && env.production === 'true');
const outputDir = (env && env.outputDir) || path.join(__dirname, '..', 'public', 'assets', 'webpack');
const licenseReportFile = (env && env.licenseReportFile) || path.join(__dirname, '..', 'yarn-license-report', `used-packages-${production ? 'prod' : 'dev'}.json`);
console.log(`Generating assets in ${outputDir}`); //eslint-disable-line no-console
const entries = _.reduce(fs.readdirSync(singlePageAppModuleDir), (memo, file) => {
const fileName = path.basename(file);
const moduleName = `single_page_apps/${_.split(fileName, '.')[0]}`;
memo[moduleName] = path.join(singlePageAppModuleDir, file);
return memo;
}, {});
const assetsDir = path.join(__dirname, '..', 'webpack');
const plugins = [];
plugins.push(new HappyPack({
loaders: [{
loader: 'babel-loader',
options: {
cacheDirectory: path.join(__dirname, '..', 'tmp', 'babel-loader')
}
}],
threads: 4
}));
plugins.push(new StatsPlugin('manifest.json', {
chunkModules: false,
source: false,
chunks: false,
modules: false,
assets: true
}));
plugins.push(new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}));
plugins.push(new webpack.optimize.CommonsChunkPlugin({
name: "vendor-and-helpers.chunk",
filename: production ? '[name]-[chunkhash].js' : '[name].js',
minChunks(module, _count) {
function isFromNPM() {
return new RegExp(`node_modules`).test(module.resource) || new RegExp(`node-vendor`).test(module.resource);
}
function isInside() {
return module.resource.indexOf(path.join(assetsDir, ..._(Array.prototype.concat.apply([], arguments)).flattenDeep().compact().value())) === 0;
}
return module.resource && (isFromNPM() || isInside('helpers') || isInside('gen') || isInside('models', 'shared') || isInside('models', 'mixins') || isInside('views', 'shared'));
},
}));
if (production) {
plugins.push(new UglifyJsPlugin({
cache: path.join(__dirname, '..', 'tmp', 'uglify-js-cache'),
parallel: true,
sourceMap: true,
uglifyOptions: {
ecma: 5,
warnings: false
}
}));
plugins.push(new webpack.LoaderOptionsPlugin({minimize: true}));
plugins.push(new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production')}}));
plugins.push(new webpack.NoEmitOnErrorsPlugin());
}
const config = {
cache: true,
bail: true,
entry: entries,
output: {
path: outputDir,
publicPath: '/go/assets/webpack/',
filename: production ? '[name]-[chunkhash].js' : '[name].js'
},
resolve: {
modules: _.compact([
assetsDir,
production ? null : path.join(__dirname, '..', 'spec', 'webpack', 'patches'), // provide monkey patches libs for tests
'node_modules']),
extensions: ['.js', '.js.msx', '.msx', '.es6'],
alias: {
'string-plus': 'helpers/string-plus',
'string': 'underscore.string',
'jQuery': 'jquery',
}
},
devServer: {
hot: false,
inline: false
},
plugins,
module: {
rules: [
{
test: /\.(msx|js)$/,
exclude: /node_modules/,
use: 'happypack/loader',
}
]
}
};
const LicensePlugin = function (_options) {
this.apply = function (compiler) {
licenseChecker.init({json: true, production: false, start: process.cwd()}, (err, licenseData) => {
if (err) {
console.error('Found error');
console.error(err);
process.exit(1);
}
const filenames = [];
compiler.plugin("emit", (compilation, callback) => {
compilation.chunks.forEach((chunk) => {
chunk.modulesIterable.forEach((chunkModule) => {
filenames.push(chunkModule.resource || (chunkModule.rootModule && chunkModule.rootModule.resource));
if (Array.isArray(chunkModule.fileDependencies)) {
chunkModule.fileDependencies.forEach((e) => {
filenames.push(e);
});
}
});
});
callback();
const licenseReport = _.chain(filenames)
.uniq()
.filter((fileName) => fileName && fileName.indexOf('node_modules') >= 0)
.map((fileName) => {
const file = upath.normalize(fileName).replace(upath.join(process.cwd(), '/node_modules/'), '');
return file.startsWith("@") ? file.split("/").slice(0, 2).join("/") : file.split("/")[0];
})
.uniq()
.sort()
.reduce((accumulator, moduleName) => {
const moduleNameWithVersion = _(licenseData).findKey((moduleLicenseInfo, moduleNameWithVersion) => {
return moduleNameWithVersion.startsWith(`${moduleName}@`);
});
const licenseDataForModule = licenseData[moduleNameWithVersion];
if (licenseDataForModule) {
const moduleVersion = moduleNameWithVersion.split('@')[1];
if (licenseDataForModule.licenseFile) {
const licenseReportDirForModule = path.join(path.dirname(licenseReportFile), `${moduleName}-${moduleVersion}`);
fsExtra.removeSync(licenseReportDirForModule);
fsExtra.mkdirsSync(licenseReportDirForModule);
fsExtra.copySync(licenseDataForModule.licenseFile, path.join(licenseReportDirForModule, path.basename(licenseDataForModule.licenseFile)));
}
accumulator[moduleName] = {
moduleName: moduleName,
moduleVersion: moduleVersion,
moduleUrls: [licenseDataForModule.repository],
moduleLicenses: [
{
moduleLicense: licenseDataForModule.licenses,
moduleLicenseUrl: `https://spdx.org/licenses/${licenseDataForModule.licenses}.html`
}
]
};
} else {
console.error(`Unable to find license data for ${moduleName}`);
process.exit(1);
}
return accumulator;
}, {}).value();
fs.writeFileSync(licenseReportFile, `${JSON.stringify(licenseReport, null, 2)}\n`);
});
});
};
};
config.plugins.push(new LicensePlugin());
if (production) {
fsExtra.removeSync(config.output.path);
config.devtool = "source-map";
} else {
config.devtool = "inline-source-map";
config.resolve.modules.push(path.join(__dirname, 'spec', 'webpack'));
const jasmineCore = require('jasmine-core');
const jasmineFiles = jasmineCore.files;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const jasmineIndexPage = {
inject: true,
xhtml: true,
filename: '_specRunner.html',
template: path.join(__dirname, '..', 'spec', 'webpack', '_specRunner.html.ejs'),
jasmineJsFiles: _.map(jasmineFiles.jsFiles.concat(jasmineFiles.bootFiles), (file) => {
return `__jasmine/${file}`;
}),
jasmineCssFiles: _.map(jasmineFiles.cssFiles, (file) => {
return `__jasmine/${file}`;
}),
excludeChunks: _.keys(entries)
};
config.plugins.push(new HtmlWebpackPlugin(jasmineIndexPage));
config.entry['specRoot'] = path.join(__dirname, '..', 'spec', 'webpack', 'specRoot.js');
const JasmineAssetsPlugin = function (_options) {
this.apply = function (compiler) {
compiler.plugin('emit', (compilation, callback) => {
const allJasmineAssets = jasmineFiles.jsFiles.concat(jasmineFiles.bootFiles).concat(jasmineFiles.cssFiles);
_.each(allJasmineAssets, (asset) => {
const file = path.join(jasmineFiles.path, asset);
const contents = fs.readFileSync(file).toString();
compilation.assets[`__jasmine/${asset}`] = {
source() {
return contents;
},
size() {
return contents.length;
}
};
});
callback();
});
};
};
config.plugins.push(new JasmineAssetsPlugin());
}
return config;
};