1 | const { join } = require('path');
|
2 | const { copySync, writeFileSync, readJSONSync, readFileSync } = require('fs-extra');
|
3 | const { minify } = require('terser');
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | const runtime = 'jsx2mp-runtime';
|
10 | const runtimePackageJSONPath = require.resolve(join(runtime, 'package.json'));
|
11 | const runtimePackageJSON = readJSONSync(runtimePackageJSONPath);
|
12 | const runtimePackagePath = join(runtimePackageJSONPath, '..');
|
13 |
|
14 | module.exports = class JSX2MPRuntimePlugin {
|
15 | constructor({ platform = 'ali', mode = 'build' }) {
|
16 | this.platform = platform;
|
17 | this.mode = mode;
|
18 | }
|
19 |
|
20 | apply(compiler) {
|
21 | compiler.hooks.emit.tapAsync(
|
22 | 'JSX2MPRuntimePlugin',
|
23 | (compilation, callback) => {
|
24 | const runtimeTargetPath = runtimePackageJSON.miniprogram && runtimePackageJSON.miniprogram[this.platform]
|
25 | ? runtimePackageJSON.miniprogram[this.platform]
|
26 | : runtimePackageJSON.main || 'index.js';
|
27 | const sourceFile = require.resolve(join(runtimePackagePath, runtimeTargetPath));
|
28 | const targetFile = join(compiler.outputPath, 'npm', runtime + '.js');
|
29 |
|
30 | if (this.mode === 'build') {
|
31 | const sourceCode = minify(readFileSync(sourceFile, 'utf-8')).code;
|
32 | writeFileSync(targetFile, sourceCode);
|
33 | } else {
|
34 | copySync(sourceFile, targetFile);
|
35 | }
|
36 | callback();
|
37 | }
|
38 | );
|
39 | }
|
40 | };
|