Created
December 20, 2016 16:43
-
-
Save shellscape/a7461022503f019598be93a512a1901a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A webpack plugin for specifying multiple dependencies for a single | |
* variable. | |
* | |
* plugins: [ | |
* new ProvideMultiPlugin({ | |
* 'gilt': [ 'internal.gilt_require', 'internal.require' ] | |
* }) | |
* ] | |
* | |
*/ | |
'use strict'; | |
const webpack = require('webpack'); | |
const ModuleParserHelpers = require('webpack/lib/ModuleParserHelpers'); | |
const ConstDependency = require('webpack/lib/dependencies/ConstDependency'); | |
const NullFactory = require('webpack/lib/NullFactory'); | |
class ProvideMultiPlugin { | |
constructor (definitions) { | |
this.definitions = definitions; | |
} | |
apply (compiler) { | |
compiler.plugin('compilation',(compilation) => { | |
compilation.dependencyFactories.set(ConstDependency, new NullFactory()); | |
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); | |
}); | |
Object.keys(this.definitions).forEach((name) => { | |
let requests = this.definitions[name], | |
nameParts = name.split('.'); | |
if (!Array.isArray(requests)) { | |
requests = [ requests ]; | |
} | |
if(nameParts.length > 0) { | |
nameParts.slice(1).forEach((_, i) => { | |
let name = nameParts.slice(0, i + 1).join('.'); | |
compiler.parser.plugin('can-rename ' + name, function() { | |
return true; | |
}); | |
}); | |
} | |
compiler.parser.plugin('expression ' + name, function (expr) { | |
let nameIdentifier = name, | |
scopedName = name.indexOf('.') >= 0; | |
if(scopedName) { | |
nameIdentifier = '__webpack_provided_' + name.replace(/\./g, '_dot_'); | |
} | |
for(let request of requests) { | |
if(!ModuleParserHelpers.addParsedVariable(this, nameIdentifier, 'require(' + JSON.stringify(request) + ')')) { | |
return false; | |
} | |
} | |
if(scopedName) { | |
nameIdentifier = '__webpack_provided_' + name.replace(/\./g, '_dot_'); | |
let dep = new ConstDependency(nameIdentifier, expr.range); | |
dep.loc = expr.loc; | |
this.state.current.addDependency(dep); | |
} | |
return true; | |
}); | |
}, this); | |
} | |
}; | |
module.exports = ProvideMultiPlugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment