-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
56 lines (45 loc) · 2.25 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
var dotEnv = require('dotenv');
var fs = require('fs');
var sysPath = require('path');
var process = require('process');
module.exports = function (data) {
var t = data.types;
return {
visitor: {
ImportDeclaration: function(path, state) {
var options = state.opts;
if (options.replacedModuleName === undefined)
return;
var configDir = options.configDir ? options.configDir : './';
var configFile = options.filename ? options.filename : '.env';
if (path.node.source.value === options.replacedModuleName) {
var babelEnv = process.env.BABEL_ENV;
var env = (!babelEnv || babelEnv === 'development') ? 'development' : 'production';
var platformPath = configFile + '.' + env;
if (process.env.ENV_FILE) {
platformPath = process.env.ENV_FILE;
}
var config = dotEnv.config({ path: sysPath.join(configDir, configFile), silent: true }) || {};
var config = Object.assign(config, dotEnv.config({ path: sysPath.join(configDir, platformPath), silent: true }));
path.node.specifiers.forEach(function(specifier, idx){
if (specifier.type === "ImportDefaultSpecifier") {
throw path.get('specifiers')[idx].buildCodeFrameError('Import dotenv as default is not supported.')
}
var importedId = specifier.imported.name
var localId = specifier.local.name;
if(!config[importedId]) {
throw path.get('specifiers')[idx].buildCodeFrameError('Try to import dotenv variable "' + importedId + '" which is not defined in any ' + configFile + ' files.')
}
var binding = path.scope.getBinding(localId);
binding.referencePaths.forEach(function(refPath){
if (config[importedId]) {
refPath.replaceWith(t.valueToNode(config[importedId]))
}
});
})
path.remove();
}
}
}
}
}