-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
86 lines (71 loc) · 2.3 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
74
75
76
77
78
79
80
81
82
83
84
85
86
const {readFileSync} = require('fs')
const process = require('process')
const dotenv = require('dotenv')
function parseDotenvFile(path) {
let content
try {
content = readFileSync(path)
} catch {
// The env file does not exist.
return {}
}
return dotenv.parse(content)
}
module.exports = ({types: t}) => ({
name: 'dotenv-import',
pre() {
this.opts = {
moduleName: '@env',
path: '.env',
allowlist: null,
blocklist: null,
safe: false,
allowUndefined: false,
...this.opts,
}
if (this.opts.safe) {
this.env = parseDotenvFile(this.opts.path)
} else {
dotenv.config({
path: this.opts.path,
})
this.env = process.env
}
},
visitor: {
ImportDeclaration(path, {opts}) {
if (path.node.source.value === opts.moduleName) {
for (const [idx, specifier] of path.node.specifiers.entries()) {
if (specifier.type === 'ImportDefaultSpecifier') {
throw path.get('specifiers')[idx].buildCodeFrameError('Default import is not supported')
}
if (specifier.type === 'ImportNamespaceSpecifier') {
throw path
.get('specifiers')
[idx].buildCodeFrameError('Wildcard import is not supported')
}
const importedId = specifier.imported.name
const localId = specifier.local.name
if (Array.isArray(opts.allowlist) && !opts.allowlist.includes(importedId)) {
throw path
.get('specifiers')
[idx].buildCodeFrameError(`"${importedId}" was not allowlisted`)
}
if (Array.isArray(opts.blocklist) && opts.blocklist.includes(importedId)) {
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was blocklisted`)
}
if (!opts.allowUndefined && !Object.prototype.hasOwnProperty.call(this.env, importedId)) {
throw path
.get('specifiers')
[idx].buildCodeFrameError(`"${importedId}" is not defined in ${opts.path}`)
}
const binding = path.scope.getBinding(localId)
for (const refPath of binding.referencePaths) {
refPath.replaceWith(t.valueToNode(this.env[importedId]))
}
}
path.remove()
}
},
},
})