diff --git a/custom.js b/custom.js index 4b6c490..3a3394b 100644 --- a/custom.js +++ b/custom.js @@ -1,11 +1,9 @@ var through = require('through') - , recast = require('recast') , xtend = require('xtend') + , jstransform = require('jstransform') + , createVisitors = require('./visitors') -var types = recast.types.namedTypes - , build = recast.types.builders - , traverse = recast.types.traverse - , processEnvPattern = /\bprocess\.env\b/ +var processEnvPattern = /\bprocess\.env\b/ module.exports = function(rootEnv) { rootEnv = rootEnv || process.env || {} @@ -28,28 +26,7 @@ module.exports = function(rootEnv) { var source = buffer.join('') if (processEnvPattern.test(source)) { - var ast = recast.parse(source) - - traverse(ast, function(node) { - if ( - types.MemberExpression.check(node) - && !node.computed - && types.Identifier.check(node.property) - && types.MemberExpression.check(node.object) - && types.Identifier.check(node.object.object) - && node.object.object.name === 'process' - && types.Identifier.check(node.object.property) - && node.object.property.name === 'env' - ) { - var key = node.property.name - if (key in env) { - this.replace(build.literal(env[key])) - return false - } - } - }); - - source = recast.print(ast).code + source = jstransform.transform(createVisitors(env), source).code; } this.queue(source) diff --git a/package.json b/package.json index 655892f..5077a59 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "dependencies": { "xtend": "~2.1.2", "through": "~2.3.4", - "recast": "~0.5.6" + "esprima-fb": "~3001.1.0-dev-harmony-fb", + "jstransform": "~3.0.0" }, "keywords": [ "environment", diff --git a/visitors.js b/visitors.js new file mode 100644 index 0000000..16f3213 --- /dev/null +++ b/visitors.js @@ -0,0 +1,32 @@ +var Syntax = require('esprima-fb').Syntax; +var utils = require('jstransform/src/utils'); + +function create(env) { + + function visitProcessEnv(traverse, node, path, state) { + var key = node.property.name; + if (env[key] !== undefined) { + utils.catchup(node.range[0], state); + utils.append(JSON.stringify(env[key]), state); + utils.move(node.range[1], state); + } + return false; + } + + visitProcessEnv.test = function(node, path, state) { + return ( + node.type === Syntax.MemberExpression + && !node.computed + && node.property.type === Syntax.Identifier + && node.object.type === Syntax.MemberExpression + && node.object.object.type === Syntax.Identifier + && node.object.object.name === 'process' + && node.object.property.type === Syntax.Identifier + && node.object.property.name === 'env' + ) + }; + + return [visitProcessEnv]; +} + +module.exports = create;