-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
chain.ts
563 lines (522 loc) · 14.3 KB
/
chain.ts
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import * as fs from 'fs-extra'
import * as path from 'path'
import { recursiveMerge, REG_SCRIPTS, REG_SASS_SASS, REG_SASS_SCSS, REG_LESS, REG_STYLUS, REG_STYLE, REG_MEDIA, REG_FONT, REG_IMAGE } from '@tarojs/helper'
import { getSassLoaderOption } from '@tarojs/runner-utils'
import * as CopyWebpackPlugin from 'copy-webpack-plugin'
import CssoWebpackPlugin from 'csso-webpack-plugin'
import * as sass from 'sass'
import * as HtmlWebpackPlugin from 'html-webpack-plugin'
import { partial } from 'lodash'
import { mapKeys, pipe } from 'lodash/fp'
import * as MiniCssExtractPlugin from 'mini-css-extract-plugin'
import { join, resolve } from 'path'
import * as TerserPlugin from 'terser-webpack-plugin'
import * as webpack from 'webpack'
import { PostcssOption, IPostcssOption, ICopyOptions } from '@tarojs/taro/types/compile'
import * as ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'
import MainPlugin from '../plugins/MainPlugin'
import { getPostcssPlugins } from '../config/postcss.conf'
import { Option, BuildConfig } from './types'
export const makeConfig = async (buildConfig: BuildConfig) => {
const sassLoaderOption = await getSassLoaderOption(buildConfig)
return {
...buildConfig,
sassLoaderOption
}
}
const defaultTerserOption = {
keep_fnames: true,
output: {
comments: false,
keep_quoted_props: true,
quote_keys: true,
beautify: false
},
warnings: false
}
const defaultCSSCompressOption = {
mergeRules: false,
mergeIdents: false,
reduceIdents: false,
discardUnused: false,
minifySelectors: false
}
const defaultMediaUrlLoaderOption = {
limit: 10240,
esModule: false
}
const defaultFontUrlLoaderOption = {
limit: 10240,
esModule: false
}
const defaultImageUrlLoaderOption = {
limit: 10240,
esModule: false
}
const defaultCssModuleOption: PostcssOption.cssModules = {
enable: false,
config: {
namingPattern: 'global',
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
const getLoader = (loaderName: string, options: Option) => {
return {
loader: require.resolve(loaderName),
options: options || {}
}
}
const listify = listOrItem => {
if (Array.isArray(listOrItem)) {
return listOrItem
}
return [listOrItem]
}
const getPlugin = (plugin: any, args: Option[]) => {
return {
plugin,
args
}
}
export const DEFAULT_Components = new Set<string>([
'view',
'scroll-view',
'swiper',
'cover-view',
'cover-image',
'icon',
'text',
'rich-text',
'progress',
'button',
'checkbox',
'form',
'input',
'label',
'picker',
'picker-view',
'picker-view-column',
'radio',
'radio-group',
'checkbox-group',
'slider',
'switch',
'textarea',
'navigator',
'audio',
'image',
'video',
'camera',
'live-player',
'live-pusher',
'map',
'canvas',
'open-data',
'web-view',
'swiper-item',
'movable-area',
'movable-view',
'functional-page-navigator',
'ad',
'block',
'import',
'official-account',
'editor'
])
const mergeOption = ([...options]: Option[]): Option => {
return recursiveMerge({}, ...options)
}
export const processEnvOption = partial(mapKeys as any, key => `process.env.${key}`) as any
const getStyleLoader = pipe(
mergeOption,
partial(getLoader, 'style-loader')
)
const getCssLoader = pipe(
mergeOption,
partial(getLoader, 'css-loader')
)
const getPostcssLoader = pipe(
mergeOption,
partial(getLoader, 'postcss-loader')
)
const getResolveUrlLoader = pipe(
mergeOption,
partial(getLoader, 'resolve-url-loader')
)
const getSassLoader = pipe(
mergeOption,
partial(getLoader, 'sass-loader')
)
const getLessLoader = pipe(
mergeOption,
partial(getLoader, 'less-loader')
)
const getStylusLoader = pipe(
mergeOption,
partial(getLoader, 'stylus-loader')
)
const getBabelLoader = pipe(
mergeOption,
partial(getLoader, 'babel-loader')
)
const getUrlLoader = pipe(
mergeOption,
partial(getLoader, 'url-loader')
)
const getExtractCssLoader = () => {
return {
loader: MiniCssExtractPlugin.loader
}
}
export const getMiniCssExtractPlugin = pipe(
mergeOption,
listify,
partial(getPlugin, MiniCssExtractPlugin)
)
export const getHtmlWebpackPlugin = pipe(
mergeOption,
listify,
partial(getPlugin, HtmlWebpackPlugin)
)
export const getDefinePlugin = pipe(
mergeOption,
listify,
partial(getPlugin, webpack.DefinePlugin)
)
export const getHotModuleReplacementPlugin = partial(getPlugin, webpack.HotModuleReplacementPlugin, [])
export const getTerserPlugin = ([enableSourceMap, terserOptions]) => {
return new TerserPlugin({
cache: true,
parallel: true,
sourceMap: enableSourceMap,
terserOptions: recursiveMerge({}, defaultTerserOption, terserOptions)
})
}
export const getCssoWebpackPlugin = ([cssoOption]) => {
return pipe(
mergeOption,
listify,
partial(getPlugin, CssoWebpackPlugin)
)([defaultCSSCompressOption, cssoOption])
}
export const getCopyWebpackPlugin = ({ copy, appPath }: { copy: ICopyOptions; appPath: string }) => {
const args = [
copy.patterns.map(({ from, to, ...extra }) => {
return {
from,
to: resolve(appPath, to),
context: appPath,
...extra
}
}),
copy.options
]
return partial(getPlugin, CopyWebpackPlugin)(args)
}
export const getMainPlugin = args => {
return partial(getPlugin, MainPlugin)([args])
}
export const getFastRefreshPlugin = () => {
return partial(getPlugin, ReactRefreshWebpackPlugin)([])
}
const styleModuleReg = /(.*\.module).*\.(css|s[ac]ss|less|styl)\b/
const styleGlobalReg = /(.*\.global).*\.(css|s[ac]ss|less|styl)\b/
const isNodeModule = (filename: string) => /\bnode_modules\b/.test(filename)
const taroModuleRegs = [/@tarojs[/\\_]components/, /\btaro-components\b/]
const isTaroModule = (filename: string) => taroModuleRegs.some(reg => reg.test(filename))
const defaultEsnextModuleRegs = [
/@tarojs[/\\_]components/,
/\btaro-components\b/,
/@tarojs[/\\_]taro-h5/,
/\btaro-h5\b/,
/@tarojs[/\\_]router/,
/\btaro-router\b/,
/@tarojs[/\\_]redux-h5/,
/\btaro-redux-h5\b/,
/@tarojs[/\\_]mobx-h5/,
/\btaro-mobx-h5\b/
]
const getEsnextModuleRules = esnextModules => {
return [...defaultEsnextModuleRegs, ...esnextModules]
}
export const getModule = (appPath: string, {
staticDirectory,
designWidth,
deviceRatio,
enableExtract,
enableSourceMap,
styleLoaderOption,
cssLoaderOption,
lessLoaderOption,
sassLoaderOption,
stylusLoaderOption,
fontUrlLoaderOption,
imageUrlLoaderOption,
mediaUrlLoaderOption,
esnextModules = [] as (string | RegExp)[],
postcss
}) => {
const postcssOption: IPostcssOption = postcss || {}
const defaultStyleLoaderOption = {
/**
* 移除singleton设置,会导致样式库优先级发生错误
* singleton: true
*/
}
const cssModuleOptions: PostcssOption.cssModules = recursiveMerge(
{},
defaultCssModuleOption,
postcssOption.cssModules
)
const { namingPattern, generateScopedName } = cssModuleOptions.config!
const cssOptions = [
{
importLoaders: 1,
sourceMap: enableSourceMap,
modules: false
},
cssLoaderOption
]
const cssOptionsWithModule = [
Object.assign(
{
importLoaders: 1,
sourceMap: enableSourceMap,
modules: {
mode: namingPattern === 'module' ? 'local' : 'global'
}
},
{
modules: typeof generateScopedName === 'function'
? { getLocalIdent: (context, _, localName) => generateScopedName(localName, context.resourcePath) }
: { localIdentName: generateScopedName }
}
),
cssLoaderOption
]
const esnextModuleRules = getEsnextModuleRules(esnextModules)
/**
* isEsnextModule
*
* 使用正则匹配判断是否是es模块
* 规则参考:https://github.com/webpack/webpack/blob/master/lib/RuleSet.js#L413
*/
const isEsnextModule = (filename: string) =>
esnextModuleRules.some(pattern => {
if (pattern instanceof RegExp) {
return pattern.test(filename)
} else {
return filename.indexOf(pattern) > -1
}
})
const styleLoader = getStyleLoader([defaultStyleLoaderOption, styleLoaderOption])
const topStyleLoader = getStyleLoader([defaultStyleLoaderOption, {
insert: function insertAtTop (element) {
// eslint-disable-next-line no-var
var parent = document.querySelector('head')
if (parent) {
// eslint-disable-next-line no-var
var lastInsertedElement = (window as any)._lastElementInsertedByStyleLoader
if (!lastInsertedElement) {
parent.insertBefore(element, parent.firstChild)
} else if (lastInsertedElement.nextSibling) {
parent.insertBefore(element, lastInsertedElement.nextSibling)
} else {
parent.appendChild(element)
}
(window as any)._lastElementInsertedByStyleLoader = element
}
}
}, styleLoaderOption])
const extractCssLoader = getExtractCssLoader()
const lastStyleLoader = enableExtract ? extractCssLoader : styleLoader
/**
* css-loader 1.0.0版本移除了minimize选项...升级需谨慎
*
* https://github.com/webpack-contrib/css-loader/releases/tag/v1.0.0
*/
const cssLoader = getCssLoader(cssOptions)
const cssLoaders: {
include?
use
}[] = [
{
use: [cssLoader]
}
]
if (cssModuleOptions.enable) {
const cssLoaderWithModule = getCssLoader(cssOptionsWithModule)
let cssModuleCondition
if (cssModuleOptions.config!.namingPattern === 'module') {
/* 不排除 node_modules 内的样式 */
cssModuleCondition = styleModuleReg
} else {
cssModuleCondition = {
and: [{ exclude: styleGlobalReg }, { exclude: [isNodeModule] }]
}
}
cssLoaders.unshift({
include: [cssModuleCondition],
use: [cssLoaderWithModule]
})
}
const postcssLoader = getPostcssLoader([
{ sourceMap: enableSourceMap },
{
ident: 'postcss',
plugins: getPostcssPlugins(appPath, {
designWidth,
deviceRatio,
postcssOption
})
}
])
const resolveUrlLoader = getResolveUrlLoader([{}])
const baseSassOptions = {
sourceMap: true,
implementation: sass,
sassOptions: {
outputStyle: 'expanded',
fiber: false,
importer (url, prev, done) {
// 让 sass 文件里的 @import 能解析小程序原生样式文体,如 @import "a.wxss";
const extname = path.extname(url)
// fix: @import 文件可以不带scss/sass缀,如: @import "define";
if (extname === '.scss' || extname === '.sass' || extname === '.css' || !extname) {
return null
} else {
const filePath = path.resolve(path.dirname(prev), url)
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
console.log(err)
return null
} else {
fs.readFile(filePath)
.then(res => {
done({ contents: res.toString() })
})
.catch(err => {
console.log(err)
return null
})
}
})
}
}
}
}
const sassLoader = getSassLoader([baseSassOptions, {
sassOptions: {
indentedSyntax: true
}
}, sassLoaderOption])
const scssLoader = getSassLoader([baseSassOptions, sassLoaderOption])
const lessLoader = getLessLoader([{ sourceMap: enableSourceMap }, lessLoaderOption])
const stylusLoader = getStylusLoader([{ sourceMap: enableSourceMap }, stylusLoaderOption])
const rule: {
[key: string]: any
} = {}
rule.taroStyle = {
test: REG_STYLE,
use: [topStyleLoader],
include: [(filename: string) => isTaroModule(filename)]
}
rule.customStyle = {
test: REG_STYLE,
use: [lastStyleLoader],
exclude: [(filename: string) => isTaroModule(filename)]
}
rule.css = {
test: REG_STYLE,
oneOf: cssLoaders
}
rule.postcss = {
test: REG_STYLE,
use: [postcssLoader],
exclude: [
filename => {
if (isTaroModule(filename)) {
return true
} else if (isEsnextModule(filename)) {
return false
} else {
return isNodeModule(filename)
}
}
]
}
rule.sass = {
test: REG_SASS_SASS,
use: [resolveUrlLoader, sassLoader]
}
rule.scss = {
test: REG_SASS_SCSS,
use: [resolveUrlLoader, scssLoader]
}
rule.less = {
test: REG_LESS,
use: [lessLoader]
}
rule.styl = {
test: REG_STYLUS,
use: [stylusLoader]
}
rule.script = {
test: REG_SCRIPTS,
exclude: [filename => /@tarojs\/components/.test(filename) || (/node_modules/.test(filename) && !(/taro/.test(filename)))],
use: {
babelLoader: getBabelLoader([{
compact: false
}])
}
}
rule.media = {
test: REG_MEDIA,
use: {
urlLoader: getUrlLoader([
defaultMediaUrlLoaderOption,
{
name: `${staticDirectory}/media/[name].[ext]`,
...mediaUrlLoaderOption
}
])
}
}
rule.font = {
test: REG_FONT,
use: {
urlLoader: getUrlLoader([
defaultFontUrlLoaderOption,
{
name: `${staticDirectory}/fonts/[name].[ext]`,
...fontUrlLoaderOption
}
])
}
}
rule.image = {
test: REG_IMAGE,
use: {
urlLoader: getUrlLoader([
defaultImageUrlLoaderOption,
{
name: `${staticDirectory}/images/[name].[ext]`,
...imageUrlLoaderOption
}
])
}
}
return { rule }
}
export const getOutput = (appPath: string, [{ outputRoot, publicPath, chunkDirectory }, customOutput]) => {
return {
path: join(appPath, outputRoot),
filename: 'js/[name].js',
chunkFilename: `${chunkDirectory}/[name].js`,
publicPath,
...customOutput
}
}
export const getDevtool = ({ enableSourceMap, sourceMapType = 'cheap-module-eval-source-map' }) => {
return enableSourceMap ? sourceMapType : 'none'
}