forked from megalojs/megalo-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
274 lines (244 loc) · 8.02 KB
/
index.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
const fs = require('fs')
const chalk = require('chalk')
const path = require('path')
const { getCssExt } = require('@megalo/cli-share-utils')
const { findExisting, checkFileExistsSync } = require('./utils')
module.exports = (api, options) => {
const platform = process.env.PLATFORM
const cssExt = getCssExt(platform)
const isProd = process.env.NODE_ENV === 'production'
api.chainWebpack(chainConfig => {
if (platform === 'web') {
const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const TerserPlugin = require('terser-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const target = createTarget()
// 检查入口文件
resolveEntry()
// web使用生成的入口文件
chainConfig.entry('index')
.add(api.resolve('.megalo-tmp/webEntry.js'))
chainConfig
.devtool(isProd && !options.productionSourceMap ? 'none' : 'source-map')
.target(target)
.output
.path(api.resolve(`dist-${platform}/`))
.filename(isProd ? '[name].[contenthash].js' : '[name].js')
.chunkFilename(isProd ? '[name].[id].[contenthash].js' : '[name].[id].js')
// web dev环境添加dev-server
!isProd && chainConfig
.devServer
.open(true)
// 提取公共文件、压缩混淆
chainConfig.optimization
.noEmitOnErrors(true)
.runtimeChunk({ name: 'runtime' })
.splitChunks({
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]|megalo[\\/]/,
name: 'vendor',
chunks: 'initial'
},
common: {
name: 'common',
minChunks: 2
}
}
})
.when(isProd, optimization => {
optimization
.minimizer('optimize-js')
.use(
TerserPlugin,
[{
cache: true,
parallel: true,
sourceMap: options.productionSourceMap
}]
)
.end()
.minimizer('optimize-css')
.use(
OptimizeCSSAssetsPlugin,
[{
assetNameRegExp: new RegExp(`\\.${getCssExt(platform)}$`, 'g'),
cssProcessorPluginOptions: {
preset: ['default', {
discardComments: { removeAll: true },
calc: false
}]
}
}]
)
})
// 处理.vue
chainConfig.module
.rule('vue')
.test(/\.vue$/)
.use('vue')
.loader('vue-loader')
.options({
compilerOptions: {
preserveWhitespace: false
}
})
// babel
chainConfig.module
.rule('js')
.test(/\.(ts|js)x?$/)
.use('babel')
.loader('babel-loader')
// css相关loader
generateCssLoaders(chainConfig)
// 图片
chainConfig.module
.rule('picture')
.test(/\.(png|jpe?g|gif)$/i)
.use('url')
.loader('url-loader')
.options({
limit: 8192,
// TODO 这里有个小bug, static的图片会生成在dist下面的src目录,子包的图片会生成在子包下的src目录,不影响分包策略,仅仅是路径看着有些别扭
name: '[path][name].[ext]'
})
// 插件
chainConfig
.plugin('process-plugin')
.use(webpack.ProgressPlugin)
.end()
.plugin('vue-loader-plugin')
.use(VueLoaderPlugin)
.end()
.plugin('mini-css-extract-plugin')
.use(MiniCssExtractPlugin, [{ filename: `static/css/[name].${cssExt}` }])
.end()
.plugin('html-webpack-plugin')
.use(HtmlWebpackPlugin, [{
filename: 'index.html',
template: 'src/web/index.html'
}])
.end()
.plugin('copy-webpack-plugin')
.use(CopyWebpackPlugin, [{
from: 'src/static', to: 'static'
}])
chainConfig.stats({
all: false,
modules: false,
maxModules: 0,
errors: true,
warnings: true,
moduleTrace: false,
errorDetails: true
})
// megalo 周边
// 启用 @Megalo/API
const megaloAPIPath = checkFileExistsSync(`node_modules/@megalo/api/platforms/${platform}`)
if (megaloAPIPath) {
chainConfig.plugin('provide-plugin')
.use(webpack.ProvidePlugin, [{ 'Megalo': [megaloAPIPath, 'default'] }])
}
// 拷贝原生小程序组件 TODO: 拷贝前可对其进行预处理(babel转译\混淆\压缩等)
const nativeDir = checkFileExistsSync(path.join(options.nativeDir, platform)) || checkFileExistsSync(options.nativeDir)
if (nativeDir) {
chainConfig.plugin('copy-webpack-plugin')
.use(
CopyWebpackPlugin,
[
[
{
context: nativeDir,
from: `**/*`,
to: api.resolve(`dist-${platform}/native`)
}
]
]
)
}
}
})
function resolveEntry () {
// app entry
const entryContext = api.resolve('src')
const appEntry = findExisting(entryContext, [
'app.js',
'App.vue'
])
if (!appEntry) {
console.log(chalk.red(`Failed to locate entry file in ${chalk.yellow(entryContext)}.`))
console.log(chalk.red(`Valid entry file should be one of: app.js, App.vue.`))
process.exit(1)
}
const appEntryPath = path.join(entryContext, appEntry)
if (!fs.existsSync(appEntryPath)) {
console.log(chalk.red(`Entry file ${chalk.yellow(appEntry)} does not exist.`))
process.exit(1)
}
// 页面entry
const { pagesEntry } = require('@megalo/entry')
return { appEntry: appEntryPath, pagesEntry: pagesEntry(appEntryPath, options) }
}
function createTarget () {
const createMegaloTarget = require('megalo-target-debug')
const targetConfig = {
platform,
compiler: require('vue-template-compiler'),
projectOptions: options
}
return createMegaloTarget(targetConfig)
}
/**
* 生成css相关的 Loader
*
*/
function generateCssLoaders (chainConfig, projectOptions = options) {
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const merge = require('deepmerge')
const neededLoader = new Map([
['css', /\.css$/],
['less', /\.less$/],
['sass', /\.scss$/],
['stylus', /\.styl(us)?$/]
])
for (const [loaderName, loaderReg] of neededLoader) {
chainConfig.module
.rule(loaderName)
.test(loaderReg)
.use('MiniCssExtractPlugin')
.loader(MiniCssExtractPlugin.loader)
.end()
.use('css')
.loader('css-loader')
.when(projectOptions.css.loaderOptions['css'], config => {
config.tap(options => merge(options, projectOptions.css.loaderOptions['css']))
})
.end()
.use('postcss')
.loader('postcss-loader')
.options({
plugins: () => [
require('autoprefixer')(),
require('postcss-plugin-px2rem')({
rootValue: 75,
propBlackList: ['border']
})
]
})
.end()
.when(loaderName !== 'css', config => {
config.use(loaderName)
.loader(`${loaderName}-loader`)
.when(projectOptions.css.loaderOptions[loaderName], config => {
config.tap(options => merge(options, projectOptions.css.loaderOptions[loaderName]))
})
.end()
})
}
return chainConfig.module.toConfig().rules
}
}