-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (51 loc) · 1.41 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
'use strict';
const {Linter} = require('eslint');
const linter = new Linter();
const linterConfig = {
parserOptions: {
ecmaVersion: 10
},
env: {
browser: true,
node: true,
worker: true,
serviceworker: true
},
rules: {
'no-undef': 'error'
}
};
module.exports = {
input: 'index.mjs',
output: {
file: 'index.js',
format: 'cjs',
interop: false
},
plugins: [
{
name: 'remove-unnecessary-use-strict-and-reduce-unnecessary-reassign',
generateBundle(outputOptions, {'index.js': generated}) {
let {code} = generated;
if (!code.includes('function') && !code.includes('=>')) {
code = code.replace(/^'use strict';\n*/u, '');
generated.code = code;
}
const matchedModuleExports = /\nmodule\.exports = (\w+);\n/u.exec(code);
if (!matchedModuleExports) {
return;
}
code = `${code.substring(0, matchedModuleExports.index)}${code.substring(matchedModuleExports.index + matchedModuleExports[0].length)}`;
const matchedDeclaration = new RegExp(`^(var ${matchedModuleExports[1]} = |(?=function ${matchedModuleExports[1]}\\())`, 'um').exec(code);
if (!matchedDeclaration) {
return;
}
code = `${code.substring(0, matchedDeclaration.index)}module.exports = ${code.substring(matchedDeclaration.index + matchedDeclaration[0].length)}`;
if (linter.verify(code, linterConfig).length !== 0) {
return;
}
generated.code = code;
}
}
]
};