Javascript Webpack:使用目录中的每个文件创建一个捆绑包
我正试图捆绑在网页包中的每个角度模块。我的目标是拥有一个app.js,该app.js将通过webpack与此配置捆绑在一起:Javascript Webpack:使用目录中的每个文件创建一个捆绑包,javascript,angularjs,webpack,Javascript,Angularjs,Webpack,我正试图捆绑在网页包中的每个角度模块。我的目标是拥有一个app.js,该app.js将通过webpack与此配置捆绑在一起: entry: { app: "./app/app.js" }, output: { path: "./build/ClientBin", filename: "bundle.js" }, 我将把这个捆绑脚本放在我的index.html中,这样它将成为我的应用程序的入口点。 另外,我在/app/components文件夹中有
entry: {
app: "./app/app.js"
},
output: {
path: "./build/ClientBin",
filename: "bundle.js"
},
我将把这个捆绑脚本放在我的index.html中,这样它将成为我的应用程序的入口点。
另外,我在/app/components
文件夹中有许多模块。文件夹结构类似于:
app
|--components
| |
| |--home
| | |
| | |--home.html
| | |--home.js
|--app.js
|--AppController.js
我在home.js
中需要home.html
,因此当我加载home.js
时,所有需要的文件都将加载。
问题是我有几个组件,如home
,我想告诉webpack分别捆绑每个组件,并用其包含的文件夹命名,如home
我如何配置webpack来创建这些捆绑包并将它们放入
/build/components
?您可以像这样实现您想要的:
entry: {
home: './app/app.js',
page: './page/app.js',
},
output: {
path: './build/ClientBin',
filename: '[name].js',
},
这将在输出路径上生成home.js
和page.js
。根据需要调整、概括。您可能需要将这些入口路径提取到变量,等等
请注意,只要稍加调整,您就可以准确地将捆绑包输出到所需的位置。我希望您随后会使用
路径
,比如/app/components/[name]
等等。我以编程方式定义条目。我在我的webpack.config.js中写到:
function getDirectories(srcpath) {
return fs.readdirSync(srcpath).filter(function (file) {
return fs.statSync(path.join(srcpath, file)).isDirectory();
});
}
var entry = {
app: "./app/app.ts",
vendor: ["angular", "oclazyload", "angular-new-router", "lodash"]
};
var components = getDirectories("./app/components");
for (var i = 0; i < components.length; i++) {
entry[components[i]] = "./app/components/" + components[i] + "/" + components[i] + ".ts";
}
函数getDirectories(srcpath){
返回fs.readdirSync(srcpath).filter(函数(文件){
返回fs.statSync(path.join(srcpath,file)).isDirectory();
});
}
变量项={
app:“./app/app.ts”,
供应商:[“angular”、“oclazyload”、“angular新路由器”、“lodash”]
};
var-components=getDirectories(“./app/components”);
对于(var i=0;i
然后在配置中使用entry
变量。一种更简单的方法:
在webpack.config.js
中使用globs:
下面是一个例子:
var glob = require("glob");
module.exports = {
entry: {
js: glob.sync("./app/components/**/*.js"),
}
}
要单独导出每个文件,可以使用以下代码段:
const glob = require('glob')
const path = require('path')
const entryFiles = glob.sync('./app/components/**/*.js').reduce((previousValue, currentValue, currentIndex, array) => {
return typeof previousValue === 'string' ?
{
[path.basename(previousValue, path.extname(previousValue))]: previousValue,
[path.basename(currentValue, path.extname(currentValue))]: currentValue
}
:
{ ...previousValue, [path.basename(currentValue, path.extname(currentValue))]: currentValue }
})
module.exports = {
entry: entryFiles,
resolve: {
extensions: [ '.js' ]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'build', 'ClientBin')
}
}
问题是我不知道我会有多少个条目。我已经编辑了该问题以显示我的解决方法,但我正在搜索现成的解决方案。我觉得你的解决方案不错。作为一个配置驱动的工具,Web包并不真正关心如何生成配置,只要它是正确的。听起来合乎逻辑!那么,我必须如何完成此问题工作流?我的意思是,我必须将编辑过的部分放到一个答案中?虽然接受的答案使用现成的工具,但这是迄今为止最简单的,也是我的首选答案。请确保首先使用npm安装webpack glob
npm安装webpack glob--save dev
有人能显示整个webpack.config.js
文件的样子吗?例如,输出值应该是什么?