rollup-plugin-inject
Advanced tools
Comparing version 1.4.1 to 2.0.0
# rollup-plugin-inject | ||
## 2.0.0 | ||
* Work with all file extensions, not just `.js` (unless otherwise specified via `options.include` and `options.exclude`) ([#6](https://github.com/rollup/rollup-plugin-inject/pull/6)) | ||
* Allow `*` imports ([#9](https://github.com/rollup/rollup-plugin-inject/pull/9)) | ||
* Ignore replacements that are superseded (e.g. if `Buffer.isBuffer` is replaced, ignore `Buffer` replacement) ([#10](https://github.com/rollup/rollup-plugin-inject/pull/10)) | ||
## 1.4.1 | ||
@@ -4,0 +10,0 @@ |
'use strict'; | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
var rollupPluginutils = require('rollup-pluginutils'); | ||
@@ -7,71 +9,52 @@ var path = require('path'); | ||
var acorn = require('acorn'); | ||
var MagicString = require('magic-string'); | ||
MagicString = 'default' in MagicString ? MagicString['default'] : MagicString; | ||
var MagicString = _interopDefault(require('magic-string')); | ||
var reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' '); | ||
var builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split(' '); | ||
var reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split( ' ' ); | ||
var builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split( ' ' ); | ||
var blacklisted = Object.create(null); | ||
reservedWords.concat(builtins).forEach(function (word) { | ||
return blacklisted[word] = true; | ||
}); | ||
function makeLegalIdentifier(str) { | ||
str = str.replace(/-(\w)/g, function (_, letter) { | ||
return letter.toUpperCase(); | ||
}).replace(/[^$_a-zA-Z0-9]/g, '_'); | ||
var blacklisted = Object.create( null ); | ||
reservedWords.concat( builtins ).forEach( function (word) { return blacklisted[ word ] = true; } ); | ||
if (/\d/.test(str[0]) || blacklisted[str]) str = '_' + str; | ||
function makeLegalIdentifier ( str ) { | ||
str = str | ||
.replace( /-(\w)/g, function ( _, letter ) { return letter.toUpperCase(); } ) | ||
.replace( /[^$_a-zA-Z0-9]/g, '_' ); | ||
if ( /\d/.test( str[0] ) || blacklisted[ str ] ) { str = "_" + str; } | ||
return str; | ||
} | ||
function escape(str) { | ||
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); | ||
function escape ( str ) { | ||
return str.replace( /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&' ); | ||
} | ||
function isReference(_x, _x2) { | ||
var _left; | ||
function isReference ( node, parent ) { | ||
if ( node.type === 'MemberExpression' ) { | ||
return !node.computed && isReference( node.object, node ); | ||
} | ||
var _again = true; | ||
if ( node.type === 'Identifier' ) { | ||
// TODO is this right? | ||
if ( parent.type === 'MemberExpression' ) { return parent.computed || node === parent.object; } | ||
_function: while (_again) { | ||
var node = _x, | ||
parent = _x2; | ||
_again = false; | ||
// disregard the `bar` in { bar: foo } | ||
if ( parent.type === 'Property' && node !== parent.value ) { return false; } | ||
if (node.type === 'MemberExpression') { | ||
if (!(_left = !node.computed)) { | ||
return _left; | ||
} | ||
// disregard the `bar` in `class Foo { bar () {...} }` | ||
if ( parent.type === 'MethodDefinition' ) { return false; } | ||
_x = node.object; | ||
_x2 = node; | ||
_again = true; | ||
continue _function; | ||
} | ||
// disregard the `bar` in `export { foo as bar }` | ||
if ( parent.type === 'ExportSpecifier' && node !== parent.local ) { return; } | ||
if (node.type === 'Identifier') { | ||
// TODO is this right? | ||
if (parent.type === 'MemberExpression') return parent.computed || node === parent.object; | ||
// disregard the `bar` in { bar: foo } | ||
if (parent.type === 'Property' && node !== parent.value) return false; | ||
// disregard the `bar` in `class Foo { bar () {...} }` | ||
if (parent.type === 'MethodDefinition') return false; | ||
// disregard the `bar` in `export { foo as bar }` | ||
if (parent.type === 'ExportSpecifier' && node !== parent.local) return; | ||
return true; | ||
} | ||
return true; | ||
} | ||
} | ||
function flatten(node) { | ||
var name = undefined; | ||
function flatten ( node ) { | ||
var name; | ||
var parts = []; | ||
while (node.type === 'MemberExpression') { | ||
parts.unshift(node.property.name); | ||
while ( node.type === 'MemberExpression' ) { | ||
parts.unshift( node.property.name ); | ||
node = node.object; | ||
@@ -81,10 +64,10 @@ } | ||
name = node.name; | ||
parts.unshift(name); | ||
parts.unshift( name ); | ||
return { name: name, keypath: parts.join('.') }; | ||
return { name: name, keypath: parts.join( '.' ) }; | ||
} | ||
function assign(target, source) { | ||
Object.keys(source).forEach(function (key) { | ||
target[key] = source[key]; | ||
function assign ( target, source ) { | ||
Object.keys( source ).forEach( function (key) { | ||
target[ key ] = source[ key ]; | ||
}); | ||
@@ -94,16 +77,28 @@ return target; | ||
function isArray(thing) { | ||
return Object.prototype.toString.call(thing) === '[object Array]'; | ||
function isArray ( thing ) { | ||
return Object.prototype.toString.call( thing ) === '[object Array]'; | ||
} | ||
function inject(options) { | ||
if (!options) throw new Error('Missing options'); | ||
var filter = rollupPluginutils.createFilter(options.include, options.exclude); | ||
function tryParse ( code, id ) { | ||
try { | ||
return acorn.parse( code, { | ||
ecmaVersion: 6, | ||
sourceType: 'module' | ||
}); | ||
} catch ( err ) { | ||
console.warn( ("rollup-plugin-inject: failed to parse " + id + ". Consider restricting the plugin to particular files via options.include") ); | ||
} | ||
} | ||
var modules = undefined; | ||
function inject ( options ) { | ||
if ( !options ) { throw new Error( 'Missing options' ); } | ||
if (options.modules) { | ||
var filter = rollupPluginutils.createFilter( options.include, options.exclude ); | ||
var modules; | ||
if ( options.modules ) { | ||
modules = options.modules; | ||
} else { | ||
modules = assign({}, options); | ||
modules = assign( {}, options ); | ||
delete modules.include; | ||
@@ -114,11 +109,13 @@ delete modules.exclude; | ||
// Fix paths on Windows | ||
if (path.sep !== '/') { | ||
Object.keys(modules).forEach(function (key) { | ||
var module = modules[key]; | ||
if ( path.sep !== '/' ) { | ||
Object.keys( modules ).forEach( function (key) { | ||
var module = modules[ key ]; | ||
modules[key] = isArray(module) ? [module[0].split(path.sep).join('/'), module[1]] : module.split(path.sep).join('/'); | ||
modules[ key ] = isArray( module ) ? | ||
[ module[0].split( path.sep ).join( '/' ), module[1] ] : | ||
module.split( path.sep ).join( '/' ); | ||
}); | ||
} | ||
var firstpass = new RegExp('(?:' + Object.keys(modules).map(escape).join('|') + ')', 'g'); | ||
var firstpass = new RegExp( ("(?:" + (Object.keys( modules ).map( escape ).join( '|' )) + ")"), 'g' ); | ||
var sourceMap = options.sourceMap !== false; | ||
@@ -129,27 +126,19 @@ | ||
transform: function transform(code, id) { | ||
if (!filter(id)) return null; | ||
if (code.search(firstpass) == -1) return null; | ||
if (path.extname(id) !== '.js') return null; | ||
transform: function transform ( code, id ) { | ||
if ( !filter( id ) ) { return null; } | ||
if ( code.search( firstpass ) == -1 ) { return null; } | ||
var ast = undefined; | ||
if ( path.sep !== '/' ) { id = id.split( path.sep ).join( '/' ); } | ||
try { | ||
ast = acorn.parse(code, { | ||
ecmaVersion: 6, | ||
sourceType: 'module' | ||
}); | ||
} catch (err) { | ||
err.message += ' in ' + id; | ||
throw err; | ||
} | ||
var ast = tryParse( code, id ); | ||
if ( !ast ) { return null; } | ||
// analyse scopes | ||
var scope = rollupPluginutils.attachScopes(ast, 'scope'); | ||
var scope = rollupPluginutils.attachScopes( ast, 'scope' ); | ||
var imports = {}; | ||
ast.body.forEach(function (node) { | ||
if (node.type === 'ImportDeclaration') { | ||
node.specifiers.forEach(function (specifier) { | ||
imports[specifier.local.name] = true; | ||
ast.body.forEach( function (node) { | ||
if ( node.type === 'ImportDeclaration' ) { | ||
node.specifiers.forEach( function (specifier) { | ||
imports[ specifier.local.name ] = true; | ||
}); | ||
@@ -159,66 +148,69 @@ } | ||
var magicString = new MagicString(code); | ||
var magicString = new MagicString( code ); | ||
var newImports = {}; | ||
function handleReference(node, name, keypath) { | ||
if (keypath in modules && !scope.contains(name) && !imports[name]) { | ||
var _module = modules[keypath]; | ||
if (typeof _module === 'string') _module = [_module, 'default']; | ||
function handleReference ( node, name, keypath ) { | ||
if ( keypath in modules && !scope.contains( name ) && !imports[ name ] ) { | ||
var module = modules[ keypath ]; | ||
if ( typeof module === 'string' ) { module = [ module, 'default' ]; } | ||
// prevent module from importing itself | ||
if (_module[0] === id) return; | ||
if ( module[0] === id ) { return; } | ||
var hash = keypath + ':' + _module[0] + ':' + _module[1]; | ||
var hash = keypath + ":" + (module[0]) + ":" + (module[1]); | ||
var importLocalName = name === keypath ? name : makeLegalIdentifier('$inject_' + keypath); | ||
var importLocalName = name === keypath ? name : makeLegalIdentifier( ("$inject_" + keypath) ); | ||
if (!newImports[hash]) { | ||
newImports[hash] = 'import { ' + _module[1] + ' as ' + importLocalName + ' } from \'' + _module[0] + '\';'; | ||
if ( !newImports[ hash ] ) { | ||
if ( module[1] === '*' ) { | ||
newImports[ hash ] = "import * as " + importLocalName + " from '" + (module[0]) + "';"; | ||
} else { | ||
newImports[ hash ] = "import { " + (module[1]) + " as " + importLocalName + " } from '" + (module[0]) + "';"; | ||
} | ||
} | ||
if (name !== keypath) { | ||
magicString.overwrite(node.start, node.end, importLocalName, true); | ||
if ( name !== keypath ) { | ||
magicString.overwrite( node.start, node.end, importLocalName, true ); | ||
} | ||
return true; | ||
} | ||
} | ||
estreeWalker.walk(ast, { | ||
enter: function enter(node, parent) { | ||
if (sourceMap) { | ||
magicString.addSourcemapLocation(node.start); | ||
magicString.addSourcemapLocation(node.end); | ||
estreeWalker.walk( ast, { | ||
enter: function enter ( node, parent ) { | ||
if ( sourceMap ) { | ||
magicString.addSourcemapLocation( node.start ); | ||
magicString.addSourcemapLocation( node.end ); | ||
} | ||
if (node.scope) scope = node.scope; | ||
if ( node.scope ) { scope = node.scope; } | ||
// special case – shorthand properties. because node.key === node.value, | ||
// we can't differentiate once we've descended into the node | ||
if (node.type === 'Property' && node.shorthand) { | ||
var _name = node.key.name; | ||
handleReference(node, _name, _name); | ||
if ( node.type === 'Property' && node.shorthand ) { | ||
var name = node.key.name; | ||
handleReference( node, name, name ); | ||
return this.skip(); | ||
} | ||
if (isReference(node, parent)) { | ||
var _flatten = flatten(node); | ||
var _name2 = _flatten.name; | ||
var keypath = _flatten.keypath; | ||
handleReference(node, _name2, keypath); | ||
if ( isReference( node, parent ) ) { | ||
var ref = flatten( node ); | ||
var name$1 = ref.name; | ||
var keypath = ref.keypath; | ||
var handled = handleReference( node, name$1, keypath ); | ||
if ( handled ) { return this.skip(); } | ||
} | ||
}, | ||
leave: function leave(node) { | ||
if (node.scope) scope = scope.parent; | ||
leave: function leave ( node ) { | ||
if ( node.scope ) { scope = scope.parent; } | ||
} | ||
}); | ||
var keys = Object.keys(newImports); | ||
if (!keys.length) return null; | ||
var keys = Object.keys( newImports ); | ||
if ( !keys.length ) { return null; } | ||
var importBlock = keys.map(function (hash) { | ||
return newImports[hash]; | ||
}).join('\n\n'); | ||
magicString.prepend(importBlock + '\n\n'); | ||
var importBlock = keys.map( function (hash) { return newImports[ hash ]; } ).join( '\n\n' ); | ||
magicString.prepend( importBlock + '\n\n' ); | ||
@@ -233,2 +225,2 @@ return { | ||
module.exports = inject; | ||
module.exports = inject; |
import { attachScopes, createFilter } from 'rollup-pluginutils'; | ||
import { extname, sep } from 'path'; | ||
import { sep } from 'path'; | ||
import { walk } from 'estree-walker'; | ||
@@ -7,68 +7,50 @@ import { parse } from 'acorn'; | ||
var reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' '); | ||
var builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split(' '); | ||
var reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split( ' ' ); | ||
var builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split( ' ' ); | ||
var blacklisted = Object.create(null); | ||
reservedWords.concat(builtins).forEach(function (word) { | ||
return blacklisted[word] = true; | ||
}); | ||
function makeLegalIdentifier(str) { | ||
str = str.replace(/-(\w)/g, function (_, letter) { | ||
return letter.toUpperCase(); | ||
}).replace(/[^$_a-zA-Z0-9]/g, '_'); | ||
var blacklisted = Object.create( null ); | ||
reservedWords.concat( builtins ).forEach( function (word) { return blacklisted[ word ] = true; } ); | ||
if (/\d/.test(str[0]) || blacklisted[str]) str = '_' + str; | ||
function makeLegalIdentifier ( str ) { | ||
str = str | ||
.replace( /-(\w)/g, function ( _, letter ) { return letter.toUpperCase(); } ) | ||
.replace( /[^$_a-zA-Z0-9]/g, '_' ); | ||
if ( /\d/.test( str[0] ) || blacklisted[ str ] ) { str = "_" + str; } | ||
return str; | ||
} | ||
function escape(str) { | ||
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); | ||
function escape ( str ) { | ||
return str.replace( /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&' ); | ||
} | ||
function isReference(_x, _x2) { | ||
var _left; | ||
function isReference ( node, parent ) { | ||
if ( node.type === 'MemberExpression' ) { | ||
return !node.computed && isReference( node.object, node ); | ||
} | ||
var _again = true; | ||
if ( node.type === 'Identifier' ) { | ||
// TODO is this right? | ||
if ( parent.type === 'MemberExpression' ) { return parent.computed || node === parent.object; } | ||
_function: while (_again) { | ||
var node = _x, | ||
parent = _x2; | ||
_again = false; | ||
// disregard the `bar` in { bar: foo } | ||
if ( parent.type === 'Property' && node !== parent.value ) { return false; } | ||
if (node.type === 'MemberExpression') { | ||
if (!(_left = !node.computed)) { | ||
return _left; | ||
} | ||
// disregard the `bar` in `class Foo { bar () {...} }` | ||
if ( parent.type === 'MethodDefinition' ) { return false; } | ||
_x = node.object; | ||
_x2 = node; | ||
_again = true; | ||
continue _function; | ||
} | ||
// disregard the `bar` in `export { foo as bar }` | ||
if ( parent.type === 'ExportSpecifier' && node !== parent.local ) { return; } | ||
if (node.type === 'Identifier') { | ||
// TODO is this right? | ||
if (parent.type === 'MemberExpression') return parent.computed || node === parent.object; | ||
// disregard the `bar` in { bar: foo } | ||
if (parent.type === 'Property' && node !== parent.value) return false; | ||
// disregard the `bar` in `class Foo { bar () {...} }` | ||
if (parent.type === 'MethodDefinition') return false; | ||
// disregard the `bar` in `export { foo as bar }` | ||
if (parent.type === 'ExportSpecifier' && node !== parent.local) return; | ||
return true; | ||
} | ||
return true; | ||
} | ||
} | ||
function flatten(node) { | ||
var name = undefined; | ||
function flatten ( node ) { | ||
var name; | ||
var parts = []; | ||
while (node.type === 'MemberExpression') { | ||
parts.unshift(node.property.name); | ||
while ( node.type === 'MemberExpression' ) { | ||
parts.unshift( node.property.name ); | ||
node = node.object; | ||
@@ -78,10 +60,10 @@ } | ||
name = node.name; | ||
parts.unshift(name); | ||
parts.unshift( name ); | ||
return { name: name, keypath: parts.join('.') }; | ||
return { name: name, keypath: parts.join( '.' ) }; | ||
} | ||
function assign(target, source) { | ||
Object.keys(source).forEach(function (key) { | ||
target[key] = source[key]; | ||
function assign ( target, source ) { | ||
Object.keys( source ).forEach( function (key) { | ||
target[ key ] = source[ key ]; | ||
}); | ||
@@ -91,16 +73,28 @@ return target; | ||
function isArray(thing) { | ||
return Object.prototype.toString.call(thing) === '[object Array]'; | ||
function isArray ( thing ) { | ||
return Object.prototype.toString.call( thing ) === '[object Array]'; | ||
} | ||
function inject(options) { | ||
if (!options) throw new Error('Missing options'); | ||
var filter = createFilter(options.include, options.exclude); | ||
function tryParse ( code, id ) { | ||
try { | ||
return parse( code, { | ||
ecmaVersion: 6, | ||
sourceType: 'module' | ||
}); | ||
} catch ( err ) { | ||
console.warn( ("rollup-plugin-inject: failed to parse " + id + ". Consider restricting the plugin to particular files via options.include") ); | ||
} | ||
} | ||
var modules = undefined; | ||
function inject ( options ) { | ||
if ( !options ) { throw new Error( 'Missing options' ); } | ||
if (options.modules) { | ||
var filter = createFilter( options.include, options.exclude ); | ||
var modules; | ||
if ( options.modules ) { | ||
modules = options.modules; | ||
} else { | ||
modules = assign({}, options); | ||
modules = assign( {}, options ); | ||
delete modules.include; | ||
@@ -111,11 +105,13 @@ delete modules.exclude; | ||
// Fix paths on Windows | ||
if (sep !== '/') { | ||
Object.keys(modules).forEach(function (key) { | ||
var module = modules[key]; | ||
if ( sep !== '/' ) { | ||
Object.keys( modules ).forEach( function (key) { | ||
var module = modules[ key ]; | ||
modules[key] = isArray(module) ? [module[0].split(sep).join('/'), module[1]] : module.split(sep).join('/'); | ||
modules[ key ] = isArray( module ) ? | ||
[ module[0].split( sep ).join( '/' ), module[1] ] : | ||
module.split( sep ).join( '/' ); | ||
}); | ||
} | ||
var firstpass = new RegExp('(?:' + Object.keys(modules).map(escape).join('|') + ')', 'g'); | ||
var firstpass = new RegExp( ("(?:" + (Object.keys( modules ).map( escape ).join( '|' )) + ")"), 'g' ); | ||
var sourceMap = options.sourceMap !== false; | ||
@@ -126,27 +122,19 @@ | ||
transform: function transform(code, id) { | ||
if (!filter(id)) return null; | ||
if (code.search(firstpass) == -1) return null; | ||
if (extname(id) !== '.js') return null; | ||
transform: function transform ( code, id ) { | ||
if ( !filter( id ) ) { return null; } | ||
if ( code.search( firstpass ) == -1 ) { return null; } | ||
var ast = undefined; | ||
if ( sep !== '/' ) { id = id.split( sep ).join( '/' ); } | ||
try { | ||
ast = parse(code, { | ||
ecmaVersion: 6, | ||
sourceType: 'module' | ||
}); | ||
} catch (err) { | ||
err.message += ' in ' + id; | ||
throw err; | ||
} | ||
var ast = tryParse( code, id ); | ||
if ( !ast ) { return null; } | ||
// analyse scopes | ||
var scope = attachScopes(ast, 'scope'); | ||
var scope = attachScopes( ast, 'scope' ); | ||
var imports = {}; | ||
ast.body.forEach(function (node) { | ||
if (node.type === 'ImportDeclaration') { | ||
node.specifiers.forEach(function (specifier) { | ||
imports[specifier.local.name] = true; | ||
ast.body.forEach( function (node) { | ||
if ( node.type === 'ImportDeclaration' ) { | ||
node.specifiers.forEach( function (specifier) { | ||
imports[ specifier.local.name ] = true; | ||
}); | ||
@@ -156,66 +144,69 @@ } | ||
var magicString = new MagicString(code); | ||
var magicString = new MagicString( code ); | ||
var newImports = {}; | ||
function handleReference(node, name, keypath) { | ||
if (keypath in modules && !scope.contains(name) && !imports[name]) { | ||
var _module = modules[keypath]; | ||
if (typeof _module === 'string') _module = [_module, 'default']; | ||
function handleReference ( node, name, keypath ) { | ||
if ( keypath in modules && !scope.contains( name ) && !imports[ name ] ) { | ||
var module = modules[ keypath ]; | ||
if ( typeof module === 'string' ) { module = [ module, 'default' ]; } | ||
// prevent module from importing itself | ||
if (_module[0] === id) return; | ||
if ( module[0] === id ) { return; } | ||
var hash = keypath + ':' + _module[0] + ':' + _module[1]; | ||
var hash = keypath + ":" + (module[0]) + ":" + (module[1]); | ||
var importLocalName = name === keypath ? name : makeLegalIdentifier('$inject_' + keypath); | ||
var importLocalName = name === keypath ? name : makeLegalIdentifier( ("$inject_" + keypath) ); | ||
if (!newImports[hash]) { | ||
newImports[hash] = 'import { ' + _module[1] + ' as ' + importLocalName + ' } from \'' + _module[0] + '\';'; | ||
if ( !newImports[ hash ] ) { | ||
if ( module[1] === '*' ) { | ||
newImports[ hash ] = "import * as " + importLocalName + " from '" + (module[0]) + "';"; | ||
} else { | ||
newImports[ hash ] = "import { " + (module[1]) + " as " + importLocalName + " } from '" + (module[0]) + "';"; | ||
} | ||
} | ||
if (name !== keypath) { | ||
magicString.overwrite(node.start, node.end, importLocalName, true); | ||
if ( name !== keypath ) { | ||
magicString.overwrite( node.start, node.end, importLocalName, true ); | ||
} | ||
return true; | ||
} | ||
} | ||
walk(ast, { | ||
enter: function enter(node, parent) { | ||
if (sourceMap) { | ||
magicString.addSourcemapLocation(node.start); | ||
magicString.addSourcemapLocation(node.end); | ||
walk( ast, { | ||
enter: function enter ( node, parent ) { | ||
if ( sourceMap ) { | ||
magicString.addSourcemapLocation( node.start ); | ||
magicString.addSourcemapLocation( node.end ); | ||
} | ||
if (node.scope) scope = node.scope; | ||
if ( node.scope ) { scope = node.scope; } | ||
// special case – shorthand properties. because node.key === node.value, | ||
// we can't differentiate once we've descended into the node | ||
if (node.type === 'Property' && node.shorthand) { | ||
var _name = node.key.name; | ||
handleReference(node, _name, _name); | ||
if ( node.type === 'Property' && node.shorthand ) { | ||
var name = node.key.name; | ||
handleReference( node, name, name ); | ||
return this.skip(); | ||
} | ||
if (isReference(node, parent)) { | ||
var _flatten = flatten(node); | ||
var _name2 = _flatten.name; | ||
var keypath = _flatten.keypath; | ||
handleReference(node, _name2, keypath); | ||
if ( isReference( node, parent ) ) { | ||
var ref = flatten( node ); | ||
var name$1 = ref.name; | ||
var keypath = ref.keypath; | ||
var handled = handleReference( node, name$1, keypath ); | ||
if ( handled ) { return this.skip(); } | ||
} | ||
}, | ||
leave: function leave(node) { | ||
if (node.scope) scope = scope.parent; | ||
leave: function leave ( node ) { | ||
if ( node.scope ) { scope = scope.parent; } | ||
} | ||
}); | ||
var keys = Object.keys(newImports); | ||
if (!keys.length) return null; | ||
var keys = Object.keys( newImports ); | ||
if ( !keys.length ) { return null; } | ||
var importBlock = keys.map(function (hash) { | ||
return newImports[hash]; | ||
}).join('\n\n'); | ||
magicString.prepend(importBlock + '\n\n'); | ||
var importBlock = keys.map( function (hash) { return newImports[ hash ]; } ).join( '\n\n' ); | ||
magicString.prepend( importBlock + '\n\n' ); | ||
@@ -230,2 +221,2 @@ return { | ||
export default inject; | ||
export default inject; |
{ | ||
"name": "rollup-plugin-inject", | ||
"description": "Scan modules for global variables and inject `import` statements where necessary", | ||
"version": "1.4.1", | ||
"version": "2.0.0", | ||
"devDependencies": { | ||
"eslint": "^1.7.3", | ||
"mocha": "^2.3.3", | ||
"rollup": "^0.22.0", | ||
"rollup-plugin-buble": "^0.12.1" | ||
"eslint": "^3.5.0", | ||
"mocha": "^3.0.2", | ||
"rollup": "^0.36.0", | ||
"rollup-plugin-buble": "^0.14.0" | ||
}, | ||
@@ -26,5 +26,5 @@ "main": "dist/rollup-plugin-inject.cjs.js", | ||
"dependencies": { | ||
"acorn": "^2.4.0", | ||
"acorn": "^4.0.3", | ||
"estree-walker": "^0.2.0", | ||
"magic-string": "^0.10.0", | ||
"magic-string": "^0.16.0", | ||
"rollup-pluginutils": "^1.2.0" | ||
@@ -31,0 +31,0 @@ }, |
import { attachScopes, createFilter } from 'rollup-pluginutils'; | ||
import { extname, sep } from 'path'; | ||
import { sep } from 'path'; | ||
import { walk } from 'estree-walker'; | ||
@@ -60,2 +60,13 @@ import { parse } from 'acorn'; | ||
function tryParse ( code, id ) { | ||
try { | ||
return parse( code, { | ||
ecmaVersion: 6, | ||
sourceType: 'module' | ||
}); | ||
} catch ( err ) { | ||
console.warn( `rollup-plugin-inject: failed to parse ${id}. Consider restricting the plugin to particular files via options.include` ); | ||
} | ||
} | ||
export default function inject ( options ) { | ||
@@ -96,15 +107,7 @@ if ( !options ) throw new Error( 'Missing options' ); | ||
if ( code.search( firstpass ) == -1 ) return null; | ||
if ( extname( id ) !== '.js' ) return null; | ||
let ast; | ||
if ( sep !== '/' ) id = id.split( sep ).join( '/' ); | ||
try { | ||
ast = parse( code, { | ||
ecmaVersion: 6, | ||
sourceType: 'module' | ||
}); | ||
} catch ( err ) { | ||
err.message += ` in ${id}`; | ||
throw err; | ||
} | ||
const ast = tryParse( code, id ); | ||
if ( !ast ) return null; | ||
@@ -140,3 +143,7 @@ // analyse scopes | ||
if ( !newImports[ hash ] ) { | ||
newImports[ hash ] = `import { ${module[1]} as ${importLocalName} } from '${module[0]}';`; | ||
if ( module[1] === '*' ) { | ||
newImports[ hash ] = `import * as ${importLocalName} from '${module[0]}';`; | ||
} else { | ||
newImports[ hash ] = `import { ${module[1]} as ${importLocalName} } from '${module[0]}';`; | ||
} | ||
} | ||
@@ -147,2 +154,4 @@ | ||
} | ||
return true; | ||
} | ||
@@ -170,3 +179,4 @@ } | ||
const { name, keypath } = flatten( node ); | ||
handleReference( node, name, keypath ); | ||
const handled = handleReference( node, name, keypath ); | ||
if ( handled ) return this.skip(); | ||
} | ||
@@ -173,0 +183,0 @@ }, |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No README
QualityPackage does not have a README. This may indicate a failed publish or a low quality package.
Found 1 instance in 1 package
23805
7
0
57
504
+ Addedacorn@4.0.13(transitive)
+ Addedmagic-string@0.16.0(transitive)
- Removedacorn@2.7.0(transitive)
- Removedmagic-string@0.10.2(transitive)
Updatedacorn@^4.0.3
Updatedmagic-string@^0.16.0