问题描述
我有一个表达式要求,该要求应在运行时得到解决,但对于这个简单的示例,我无法理解webpack配置:
I have an expression require which should get resolved in runtime but I can’t get my head around the webpack config for this simple example:
import something from 'module';
import pkg from './package.json';
let a;
if (pkg.main) {
a = require(pkg.main);
}
生成的构建应包含module
,但在运行时还需要./package.json
和pkg.main
作为commonjs模块-换句话说,将它们从构建中排除.
The resulting build should contain the module
but also require ./package.json
and pkg.main
in runtime as commonjs modules — in other words, exclude them from the build.
到目前为止,我的webpack.config.js
:
var webpack = require('webpack');
module.exports = {
entry: './src/main.js',
output: {
filename: '[name].js',
path: './build'
},
target: 'node-webkit',
plugins: [
new webpack.ExternalsPlugin('commonjs', './package.json')
],
module: {
noParse: /\.min\.js/,
exprContextRegExp: /$^/,
exprContextCritical: false,
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
}
]
}
};
现在发生的是webpackMissingModule
异常中对pkg.main
结果的需求,如果我删除了exprContextRegExp
,则需求将使用上下文.
What happens now is the require for pkg.main
results in webpackMissingModule
exception and if I remove exprContextRegExp
, the require will use context.
感谢您的帮助
推荐答案
对于任何想知道的人:您都可以使用此插件解决它:
For anyone wondering: you can solve it with this plugin:
function() {
this.parser.plugin('call require', function(expr) {
if (expr.arguments.length !== 1) {
return;
}
const param = this.evaluateExpression(expr.arguments[0]);
if (!param.isString() && !param.isConditional()) {
return true;
}
});
}
webpack无法解决的所有问题都将保留.
Anything that cannot be resolved by webpack will be left as is.
这篇关于Webpack需要外部表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!