UNPKG

2.83 kBJavaScriptView Raw
1let { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
2let PnpWebpackPlugin = require('pnp-webpack-plugin')
3let { promisify } = require('util')
4let escapeRegexp = require('escape-string-regexp')
5let OptimizeCss = require('optimize-css-assets-webpack-plugin')
6let { join } = require('path')
7let mkdirp = require('mkdirp')
8let fs = require('fs')
9
10let writeFile = promisify(fs.writeFile)
11
12const STATIC = /\.(eot|woff2?|ttf|otf|svg|png|jpe?g|gif|webp|mp4|mp3|ogg|pdf|html|ico|md)$/
13
14module.exports = async function getConfig(limitConfig, check, output) {
15 if (check.import) {
16 let loader = ''
17 for (let i in check.import) {
18 let list = check.import[i].replace(/}|{/g, '').trim()
19 loader +=
20 `import ${check.import[i]} from ${JSON.stringify(i)}\n` +
21 `console.log(${list})\n`
22 }
23 await mkdirp(output)
24 let entry = join(output, 'entry.js')
25 await writeFile(entry, loader)
26 check.files = entry
27 }
28
29 let config = {
30 entry: {
31 index: check.files
32 },
33 output: {
34 filename: limitConfig.why && `${limitConfig.project}.js`,
35 path: output
36 },
37 optimization: {
38 concatenateModules: !check.disableModuleConcatenation
39 },
40 resolve: {
41 plugins: [PnpWebpackPlugin]
42 },
43 resolveLoader: {
44 plugins: [PnpWebpackPlugin.moduleLoader(module)]
45 },
46 module: {
47 rules: [
48 {
49 test: STATIC,
50 use: 'file-loader'
51 },
52 {
53 test: /\.css$/,
54 exclude: /\.module\.css$/,
55 use: ['style-loader', 'css-loader']
56 },
57 {
58 test: /\.module\.css$/,
59 use: [
60 'style-loader',
61 {
62 loader: 'css-loader',
63 options: {
64 modules: true
65 }
66 }
67 ]
68 }
69 ]
70 },
71 plugins: [new OptimizeCss()]
72 }
73
74 if (check.ignore && check.ignore.length > 0) {
75 let escaped = check.ignore.map(i => escapeRegexp(i))
76 let ignorePattern = new RegExp(`^(${escaped.join('|')})($|/)`)
77 config.externals = (context, request, callback) => {
78 if (ignorePattern.test(request)) {
79 callback(null, 'root a')
80 } else {
81 callback()
82 }
83 }
84 }
85
86 if (limitConfig.why) {
87 config.plugins.push(
88 new BundleAnalyzerPlugin({
89 openAnalyzer: process.env.NODE_ENV !== 'test',
90 analyzerMode: process.env.NODE_ENV === 'test' ? 'static' : 'server',
91 defaultSizes: check.gzip === false ? 'parsed' : 'gzip',
92 analyzerPort: 8888 + limitConfig.checks.findIndex(i => i === check)
93 })
94 )
95 } else if (limitConfig.saveBundle) {
96 config.plugins.push(
97 new BundleAnalyzerPlugin({
98 openAnalyzer: false,
99 analyzerMode: 'disabled',
100 generateStatsFile: true
101 })
102 )
103 }
104
105 return config
106}