Skip to content

Commit

Permalink
🆕 Add babel-plugin-inject-node-globals
Browse files Browse the repository at this point in the history
  • Loading branch information
Steel Brain committed Sep 17, 2018
1 parent 232be98 commit 0d1476b
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/babel-plugin-inject-node-globals/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
src/
*.flow
15 changes: 15 additions & 0 deletions packages/babel-plugin-inject-node-globals/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "babel-plugin-inject-node-globals",
"version": "3.0.0-beta9",
"description": "TODO",
"repository": {
"type": "git",
"url": "git+https://github.com/steelbrain/pundle.git"
},
"main": "lib/index.js",
"flow:main": "src/index.js",
"scripts": {},
"dependencies": {},
"author": "steelbrain",
"license": "MIT"
}
59 changes: 59 additions & 0 deletions packages/babel-plugin-inject-node-globals/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// @flow
/* eslint-disable no-param-reassign,prefer-destructuring */

const INJECTION_NAMES = new Set(['setImmediate', 'clearImmediate', 'Buffer', 'process'])

function makeTemplate(template: string) {
let cachedValue
return function({ parseSync }) {
if (!cachedValue) {
cachedValue = parseSync(template).program.body[0]
}
return cachedValue
}
}

const getTimersInjection = makeTemplate(
`var __$sb$pundle$timers = require('timers'),
setImmediate = __$sb$pundle$timers.setImmediate,
clearImmediate=__$sb$pundle$timers.clearImmediate`,
)
const getBufferInjection = makeTemplate(`var Buffer = require('buffer').Buffer`)
const getProcessInjection = makeTemplate(`var process = require('process')`)

export default function getPluginInjectNodeGlobals({ parseSync }: Object) {
const injectionNames = new Set()

return {
visitor: {
Identifier(path: Object) {
const { node } = path
if (
INJECTION_NAMES.has(node.name) &&
!injectionNames.has(node.name) &&
path.isReferencedIdentifier() &&
!path.scope.hasBinding(node.name)
) {
injectionNames.add(node.name)
}
},
Program: {
exit(path: Object) {
if (!injectionNames.size) return

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

0 comments on commit 0d1476b

Please sign in to comment.