gpt4 book ai didi

javascript - Webpack 需要外部表达式

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:38 25 4
gpt4 key购买 nike

我有一个表达式 require 应该在运行时得到解析,但我无法理解这个简单示例的 webpack 配置:

import something from 'module';
import pkg from './package.json';
let a;

if (pkg.main) {
a = require(pkg.main);
}

生成的构建应包含 module,但在运行时还需要 ./package.jsonpkg.main 作为 commonjs 模块 - 在换句话说,将它们从构建中排除。

到目前为止我的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/
}
]
}
};

现在发生的情况是 pkg.main 的 require 导致 webpackMissingModule 异常,如果我删除 exprContextRegExp,则 require 将使用上下文。

感谢您的帮助

最佳答案

对于任何想知道的人:您可以使用此插件解决它:

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 无法解决的问题都将保持原样。

关于javascript - Webpack 需要外部表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38697321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com