-
Notifications
You must be signed in to change notification settings - Fork 5
/
gulpfile.js
339 lines (311 loc) · 9.09 KB
/
gulpfile.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
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
/* eslint no-console: 0, radix: 0, guard-for-in: 0, import/no-mutable-exports: 0 */
const gulp = require('gulp');
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const color = require('cli-color');
const del = require('del');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HappyPack = require('happypack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const merge = require('merge-stream');
const gulpSequence = require('gulp-sequence');
const changed = require('gulp-changed');
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const file = require('gulp-file');
const rename = require('gulp-rename');
const iconPlugin = require('./icon-plugin');
const config = require('./src/core/common/config');
// 开发
let isDev = false;
// 版本号
let revisioned = false;
let callbacked = false;
let configCallbacked = false;
let bundleAnalyzer = false;
gulp.task('clean', () => {
return del('public/**/*');
});
// 复制文件
gulp.task('copy', () => {
return merge(
// 复制图片
gulp.src('src/core/asset/img/**/*')
.pipe(changed('public/images'))
.pipe(gulp.dest('public/images')),
// 复制图标
gulp.src('src/core/asset/img/favicon.ico')
.pipe(changed('public'))
.pipe(gulp.dest('public')),
// 复制第三方包
gulp.src('src/core/vendor/**/*')
.pipe(changed('public'))
.pipe(gulp.dest('public')),
// 压缩单个JS文件
gulp.src('src/core/vendor/**/*.js')
.pipe(babel())
.pipe(uglify())
.pipe(changed('public'))
.pipe(gulp.dest('public')),
// 写入less配置
gulp.src('src/core/page/style/common/config.less')
.pipe(file('config.less', `@cdn: '${config.cdn || ''}';`))
.pipe(gulp.dest('src/core/page/style/common')),
// 生成SVG
gulp.src('src/core/asset/svg/**/*.svg')
.pipe(iconPlugin())
.pipe(rename((path) => {
path.extname = '.js';
}))
.pipe(gulp.dest('src/core/page/icon'))
);
});
// 生成新版本号
gulp.task('revision', () => {
if (revisioned) {
return;
}
// 生成版本号
const version = Math.round(Math.random() * 10000000) + 10000000;
// 替换配置信息
fs.writeFileSync(path.join(__dirname, '/version.json'), `{"version": "${version}"}`, 'utf-8');
revisioned = true;
});
// 打包项目中的三方包
gulp.task('webpack-dll', (callback) => {
webpack({
entry: {
vendors: [
'react',
'react-dom',
'react-router',
'react-router-dom',
'react-redux',
'redux',
'redux-thunk',
'lodash',
],
},
output: {
path: path.join(__dirname, 'public'),
filename: `vendors.${require('./version').version}.js`,
library: '[name]',
},
plugins: [
new webpack.DllPlugin({
path: `${__dirname}/dll-manifest.json`,
name: '[name]',
context: __dirname,
}),
(!isDev && new webpack.optimize.UglifyJsPlugin({
minimize: true,
output: {
comments: false,
},
compress: {
warnings: false,
},
})) || (() => {}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': isDev ? '"development"' : '"production"',
})
]
}, (err, stats) => {
if (err) {
console.log(err);
}
if (stats.compilation.errors.length > 0) {
console.log(stats.compilation.errors[0].message);
}
callback();
if (!err && stats.compilation.errors.length === 0) {
process.emit('webpack-rebundled');
}
});
});
// 打包移动端文件
gulp.task('webpack-page', (callback) => {
console.log({isDev});
webpack({
watch: isDev,
devtool: isDev ? 'source-map' : '',
entry: [
'./src/page/index.js',
],
output: {
path: path.join(__dirname, 'public'),
filename: `page.${require('./version').version}.js`,
publicPath: '/',
chunkFilename: 'c/[name].[chunkhash:6].chunk.js',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: [{
loader: 'happypack/loader',
options: {
id: 'js'
}
}],
}, {
test: /\.less$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'raw-loader',
options: {
minimize: !isDev,
}
},
'postcss-loader',
'less-loader',
],
fallback: 'style-loader',
}),
}, {
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'raw-loader',
options: {
minimize: !isDev,
}
},
{
loader: 'postcss-loader',
},
],
fallback: 'style-loader',
})
}, {
test: /\.(jpg|png)$/,
use: ['url-loader'],
}, {
test: /\.yml$/,
use: ['json-loader', 'yaml-loader']
}, {
test: /\.svg/,
use: ['svg-loader']
}],
},
plugins: [
bundleAnalyzer ? new BundleAnalyzerPlugin(BundleAnalyzerOptions(8880)) : (() => {}),
new HappyPack({
id: 'js',
loaders: ['babel-loader'],
}),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./dll-manifest.json'),
}),
new ExtractTextPlugin(`page.${require('./version').version}.css`),
(!isDev && new webpack.optimize.UglifyJsPlugin({
minimize: true,
output: {
comments: false,
},
compress: {
warnings: false,
},
})) || (() => {}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': isDev ? '"development"' : '"production"',
}),
],
resolve: {
extensions: ['.js', '.json', '.less', '.png', 'jpg'],
alias: {
},
},
}, (err, stats) => {
if (err) {
console.log(err);
}
if (stats.compilation.errors.length > 0) {
console.log(stats.compilation.errors[0].message);
}
if (!callbacked) {
callbacked = true;
if (err) {
callback(err);
} else if ((stats.errors || []).length > 0) {
callback(stats.errors[0]);
} else {
callback();
}
} else {
console.log(`${color.cyan('webpack-page')}: done ${color.magenta(`${stats.toJson({ timing: true }).time} ms`)}`);
}
if (!err && stats.compilation.errors.length === 0) {
process.emit('webpack-rebundled');
}
});
});
// 监听变动
gulp.task('watch', () => {
// 修改配置文件
isDev = true;
// 监听
gulp.watch([
'core/asset/img/**/*',
'core/asset/svg/**/*',
], [
'copy',
]);
});
gulp.task('analyse-option', () => {
// 修改配置文件
bundleAnalyzer = true;
});
// 启动开发服务器
gulp.task('server', () => {
process.env.NODE_ENV = 'development';
require('./index.js');
});
// 启动mock服务器
gulp.task('mock-server', () => {
process.env.NODE_ENV = 'development';
require('./mock-index');
});
// 分析打包文件
gulp.task('rebuild-icon', ['clean', 'copy']);
gulp.task('analyse', ['watch', 'analyse-option', 'revision', 'webpack-dll', 'webpack-page']);
gulp.task('dev', gulpSequence('watch', 'copy', 'revision', 'webpack-dll', 'webpack-page', 'server'));
gulp.task('mock', gulpSequence('watch', 'mock-server'));
// bundle分析器配置
function BundleAnalyzerOptions(port) {
return {
// Can be `server`, `static` or `disabled`.
// In `server` mode analyzer will start HTTP server to show bundle report.
// In `static` mode single HTML file with bundle report will be generated.
// In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
analyzerMode: 'server',
// Host that will be used in `server` mode to start HTTP server.
analyzerHost: '127.0.0.1',
// Port that will be used in `server` mode to start HTTP server.
analyzerPort: port,
// Path to bundle report file that will be generated in `static` mode.
// Relative to bundles output directory.
reportFilename: 'report.html',
// Module sizes to show in report by default.
// Should be one of `stat`, `parsed` or `gzip`.
// See "Definitions" section for more information.
defaultSizes: 'parsed',
// Automatically open report in default browser
openAnalyzer: true,
// If `true`, Webpack Stats JSON file will be generated in bundles output directory
generateStatsFile: false,
// Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
// Relative to bundles output directory.
statsFilename: 'stats.json',
// Options for `stats.toJson()` method.
// For example you can exclude sources of your modules from stats file with `source: false` option.
// See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
statsOptions: null,
// Log level. Can be 'info', 'warn', 'error' or 'silent'.
logLevel: 'info'
};
}