UNPKG

1.44 kBJavaScriptView Raw
1const { join } = require('path');
2const { copySync, writeFileSync, readJSONSync, readFileSync } = require('fs-extra');
3const { minify } = require('terser');
4
5/**
6 * Runtime packages should be a dependency of jsx2mp-cli,
7 * for convenient to copy vendors.
8 */
9const runtime = 'jsx2mp-runtime';
10const runtimePackageJSONPath = require.resolve(join(runtime, 'package.json'));
11const runtimePackageJSON = readJSONSync(runtimePackageJSONPath);
12const runtimePackagePath = join(runtimePackageJSONPath, '..');
13
14module.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};