当前从另一个文件请求对象会除去Regex键值
我目前正在遍历几个不同的目录,要求这些目录中的Webpack配置对象,并在使用给定配置对象运行webpack编译器的节点中启动子进程。
[当我使用require(webpackConfigPath)时,它会剥离module: { rules : [ { test: /\.js$/, ...} ]}
的正则表达式值,并用一个空对象替换它们,带来如下所示的内容:module: { rules : [ { test: {}, ...} ]}
有人可以指导我如何从另一个文件中深度克隆变量,而不会去除这些RegExp键值并替换为空对象吗?
用法示例:
const webpackConfigDir = path.resolve( __dirname, themeDir + '/webpack.config.js' )
let config = require( webpackConfigDir );
回答如下:我最终通过为Webpack配置要求构造函数来解决了这个问题。
实施例:
webpack.config.js
const path = require("path");
const entryPath = path.resolve( __dirname, 'source/scripts/app.js' );
const outputPath = path.resolve( __dirname, 'dist/js' )
const constructConfig = function ( entryPath, outputPath ) {
const config = {
entry: ["@babel/polyfill", entryPath],
output: {
path: outputPath,
filename: "scripts.js"
},
module: {
rules: [
{
test: /\.js$/,
use: "babel-loader",
exclude: /node_modules/
}
]
},
plugins: [],
devtool: 'source-map',
externals: {
jquery: 'jQuery'
}
}
return config
}
module.exports = {
constructor: constructConfig,
entry: entryPath,
output: outputPath
}
然后我保存了将构造函数转换为字符串的方法,因为节点子进程不允许传入函数,所以只能传入对象:
scripts.js
:
let configConstructor = require( webpackConfigDir ).constructor
let entry = require( webpackConfigDir ).entry
let output = require( webpackConfigDir ).output
let processOptions = {
constructor: configConstructor.toString(),
entry: entry,
output: output
}
process.send( processOptions )
在运行子进程的过程中,我将字符串转换回一个一旦返回就被调用的函数。
build.js
:
const webpack = require("webpack");
const chalk = require('chalk');
async function build(config) {
await webpack( config, (err, stats) => {
if ( stats.hasErrors() ) {
const errors = stats.toJson().errors
errors.forEach( (error, i) => {
console.log( chalk.white.bgRed.bold(`Error #${i + 1}: `) + chalk.white.bgRed(`${error}`) )
})
}
})
}
process.on("message", async options => {
const constructor = new Function( 'return ' + options.constructor )();
const config = await constructor( options.entry, options.output )
await build(config);
});
此解决方案可解决当前的问题,如果有人遇到类似问题,我将分享给我。在这种情况下,我试图共享项目依赖性,但允许在每个目录的基础上进行不同的Webpack配置。