gpt4 book ai didi

javascript - webpack中的多个动态入口脚本?

转载 作者:数据小太阳 更新时间:2023-10-29 04:49:12 25 4
gpt4 key购买 nike

假设我有一个这样的应用程序结构

app/
modules/
module1/
<other files>
script.js
module2/
<other files>
script.js
module3/
<other files>
script.js
lib/
<some common/shared scripts to import from>
public/
js/

如何配置 webpack 将每个 script.js(将从公共(public) lib 文件夹导入各种库/实用程序)打包并输出到这样的结构中?

例如

public/js/module1/script.js
public/js/module2/script.js

但没有单独定义每个入口文件?像 gulp 这样的东西用 /**/*.js 语法吗?

我的目标是不必在每次添加新模块/组件时都维护我的 webpack.config.js 文件。

最佳答案

您需要 glob 包并设置 entryoutput在你的webpack.config.js .webpack.config.js 时的示例在根目录中。

var webpack = require('webpack');
var glob = require('glob');

//Generate object for webpack entry
//rename './app/modules/module1/script.js' -> 'module1/script'
var entryObject = glob.sync('./app/modules/**/script.js').reduce(
function (entries, entry) {
var matchForRename = /^\.\/app\/modules\/([\w\d_]+\/script)\.js$/g.exec(entry);

if (matchForRename !== null && typeof matchForRename[1] !== 'undefined') {
entries[matchForRename[1]] = entry;
}

return entries;
},
{}
);

module.exports = {
...
entry: entryObject,//{'moduleName/script': './app/modules/moduleName/script.js', ...}
output: {
path: __dirname + '/public/js',
filename: '[name].js'//'moduleName/script.js', [name] - key from entryObject
}
...
};

如果你在 fs 上遇到错误,比如“无法解析‘fs’”添加选项

node: {
fs: "empty"
}

此外,您还可以捆绑来自 <other files> 的文件使用其他 entryObject 进入 public script.js。

var entryObject = glob.sync('./app/modules/**/*.js').reduce(
function (entries, entry) {
var matchForRename = /^\.\/app\/modules\/([\w\d_]+)\/.+\.js$/g.exec(entry);

if (matchForRename !== null && typeof matchForRename[1] !== 'undefined') {
var entryName = matchForRename[1] + '/script';

if (typeof entries[entryName] !== 'undefined') {
entries[entryName].push(entry);
} else {
entries[entryName] = [entry];
}

}

return entries;
},
{}
);

关于javascript - webpack中的多个动态入口脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37801495/

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