Skip to content

Commit

Permalink
🆕 Make state of babel plugin scoped to that execution
Browse files Browse the repository at this point in the history
  • Loading branch information
Steel Brain committed Sep 17, 2018
1 parent c08a084 commit 323c67d
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions packages/babel-plugin-inject-node-globals/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,34 +23,39 @@ const getTimersInjection = makeTemplate(
const getBufferInjection = makeTemplate(`var Buffer = require('buffer').Buffer`)
const getProcessInjection = makeTemplate(`var process = require('process')`)

export default function getPluginInjectNodeGlobals({ template }: Object) {
const injectionNames = new Set()
const INJECTIONS = Symbol('Node Global Injections')

export default function getPluginInjectNodeGlobals({ template }: Object) {
return {
visitor: {
Identifier(path: Object) {
const { node } = path
if (
INJECTION_NAMES.has(node.name) &&
!injectionNames.has(node.name) &&
!path.hub[INJECTIONS].has(node.name) &&
path.isReferencedIdentifier() &&
!path.scope.hasBinding(node.name)
) {
injectionNames.add(node.name)
path.hub[INJECTIONS].add(node.name)
}
},
Program: {
enter(path: Object) {
path.hub[INJECTIONS] = new Set()
},
exit(path: Object) {
if (!injectionNames.size) return
const injections = path.hub[INJECTIONS]

if (!injections.size) return

const statements = []
if (injectionNames.has('setImmediate') || injectionNames.has('clearImmediate')) {
if (injections.has('setImmediate') || injections.has('clearImmediate')) {
statements.push(getTimersInjection({ template }))
}
if (injectionNames.has('Buffer')) {
if (injections.has('Buffer')) {
statements.push(getBufferInjection({ template }))
}
if (injectionNames.has('process')) {
if (injections.has('process')) {
statements.push(getProcessInjection({ template }))
}
path.node.body = statements.concat(path.node.body)
Expand Down

0 comments on commit 323c67d

Please sign in to comment.