我有一个插件:
var Foo = function() {};
function lookup(key) {
// pretend this lookup function returns a different value based on key input
return 'something else';
}
Foo.prototype.apply = function() {
compiler.plugin('compilation', function(compilation, params) {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
});
compiler.parser.plugin('call abc.bar', function(expr) {
var param = this.evaluateExpression(expr.arguments[0]);
var result = lookup(param.string);
var dep = new ConstDependency(JSON.stringify(result), expr.range);
dep.loc = expr.loc;
this.state.current.addDependency(dep);
return true;
});
};
--> 当我对这个文件运行它时:
var someString = abc.bar('something');
--> 它被编译并替换为:
var someString = 'something else';
--> 但是当我这样做时:
var abc = require('abc');
var someString = abc.bar('something');
--> 它被编译为:
var abc = webpack_require(123);
var someString = abc.bar('something');
当你有一个局部变量时,发生了什么以及为什么编译器的行为会有所不同?
以及如何使替换仍然发生?
如果函数调用在对象声明中,我还看到它们被忽略:
var someObj = { someKey: abc.bar('something'); }