-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
73 lines (58 loc) · 2.23 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
63
64
65
66
67
68
69
70
71
72
73
const fs = require('fs');
const path = require('path');
// All extensions included here: https://esbuild.github.io/content-types/#javascript
const JS_EXTENSIONS = new Set(['js', 'cjs', 'mjs']);
function pluginLodashImport(options = {}) {
const { filter = /.*/, outLodashPackage = 'lodash' } = options;
return {
name: 'lodash',
setup(build) {
build.onLoad({ filter }, async args => {
const contents = await fs.promises.readFile(args.path, 'utf8');
const extension = path.extname(args.path).replace('.', '');
const loader = JS_EXTENSIONS.has(extension) ? 'jsx' : extension;
const lodashImportRegex = /import\s+?(?:(?:(?:[\w*\s{},]*)\s+from\s+?)|)[\'\"](?:(?:lodash\/?.*?))[\'\"][\s]*?(?:;|$|)/g;
const lodashImports = contents.match(lodashImportRegex);
if (!lodashImports) {
return {
loader,
contents
};
}
const destructuredImportRegex = /\{\s?(((\w+),?\s?)+)\}/g;
let finalContents = contents;
lodashImports.forEach(line => {
// Capture content inside curly braces within imports
const destructuredImports = line.match(destructuredImportRegex);
// For example:
// import noop from 'lodash/noop';
if (!destructuredImports) {
return;
}
// For example:
// import { noop, isEmpty, debounce as _debounce } from 'lodash';
const importName = destructuredImports[0]
.replace(/[{}]/g, '')
.trim()
.split(', ');
let result = '';
importName.forEach(name => {
const previousResult = `${result ? `${result}\n` : ''}`;
if (name.includes(' as ')) {
const [realName, alias] = name.split(' as ');
result = `${previousResult}import ${alias} from '${outLodashPackage}/${realName}';`;
} else {
result = `${previousResult}import ${name} from '${outLodashPackage}/${name}';`;
}
});
finalContents = contents.replace(line, result);
});
return {
loader,
contents: finalContents
};
});
},
};
}
module.exports = pluginLodashImport;