UNPKG

2.52 kBJavaScriptView Raw
1const Timer = require('../packages/utils/timer');
2const { resetNum, timerLog } = require('./logger/index');
3const setWebView = require('../packages/utils/setWebVeiw');
4const id = 'NanachiWebpackPlugin';
5const pageConfig = require('../packages/h5Helpers/pageConfig');
6const generate = require('@babel/generator').default;
7const t = require('@babel/types');
8
9class NanachiWebpackPlugin {
10 constructor({
11 platform = 'wx',
12 compress = false,
13 beta,
14 betaUi
15 } = {}) {
16 this.timer = new Timer();
17 this.nanachiOptions = {
18 platform,
19 compress,
20 beta,
21 betaUi
22 };
23 }
24 apply(compiler) {
25
26 compiler.hooks.compilation.tap(id, (compilation) => {
27 compilation.hooks.normalModuleLoader.tap(id, (loaderContext) => {
28 loaderContext.nanachiOptions = this.nanachiOptions;
29 });
30 });
31
32 // 删除webpack打包产物
33 compiler.hooks.emit.tap(id, (compilation) => {
34 if (this.nanachiOptions.platform === 'h5') {
35 // 生成pageConfig 文件 用于动态加载情况下,读取页面配置信息
36 // console.log(generate(t.exportDefaultDeclaration(pageConfig)).code);
37 const { code } = generate(t.exportDefaultDeclaration(pageConfig));
38 compilation.assets['pageConfig.js'] = {
39 source: function() {
40 return code;
41 },
42 size: function() {
43 return code.length;
44 }
45 };
46 }
47 const reg = new RegExp(compiler.options.output.filename);
48 Object.keys(compilation.assets).forEach(key => {
49 if (reg.test(key)) {
50 delete compilation.assets[key];
51 }
52 });
53 });
54
55 compiler.hooks.run.tapAsync(id, async (compilation, callback) => {
56 this.timer.start();
57 resetNum();
58 callback();
59 });
60
61 compiler.hooks.watchRun.tapAsync(id, async (compilation, callback) => {
62 this.timer.start();
63 resetNum();
64 callback();
65 });
66
67 compiler.hooks.done.tap(id, () => {
68
69 this.timer.end();
70
71 setWebView(compiler.NANACHI && compiler.NANACHI.webviews);
72
73 timerLog(this.timer);
74 });
75
76 }
77}
78
79module.exports = NanachiWebpackPlugin;
\No newline at end of file