Webpack:使用目录中的每个文件创建一个包

ali*_*ari 6 javascript angularjs webpack

我试图捆绑webpack中的每个角度模块.我的目标是有一个app.js将由webpack与这个配置捆绑在一起:

entry: {
        app: "./app/app.js"
},
output: {
        path: "./build/ClientBin",
        filename: "bundle.js"
},
Run Code Online (Sandbox Code Playgroud)

我将此捆绑脚本放在我的index.html中,这样它就是我应用的入口点.我在./app/components文件夹中有很多模块.文件夹结构如下:

app
|--components
|  |
|  |--home
|  |  |
|  |  |--home.html
|  |  |--home.js
|--app.js
|--AppController.js
Run Code Online (Sandbox Code Playgroud)

我已经要求home.htmlhome.js加载home.js所有需要的文件时加载.问题是我有几个组件home,我想告诉webpack分别捆绑每个组件,并用它包含的文件夹命名home.

如何配置webpack来创建这些包并将它们放入./build/components

Dav*_*vid 19

一种更简单的方法:

在你的使用globs webpack.config.js:

这是一个例子:

var glob = require("glob");

module.exports = {
  entry: {
     js: glob.sync("./app/components/**/*.js"),  
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 确保首先使用npm安装webpack-glob.`npm install webpack-glob --save-dev` (2认同)
  • 任何人都可以显示整个`webpack.config.js`文件的外观吗?例如,“输出”值应该是什么? (2认同)
  • 我的项目中的 `npm install webpack-glob --save-dev` 在 node_modules 中生成了 +356 个包和 +23 个漏洞,其中 2 个为严重漏洞 (2认同)
  • 是的,不要使用 webpack-glob。它不再被维护。你可以只使用`glob` (2认同)

Aci*_*dic 6

要单独导出每个文件,您可以使用以下代码片段来执行此操作:

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')
  }
}
Run Code Online (Sandbox Code Playgroud)


ali*_*ari 3

我最终以编程方式定义了条目。我在 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";
}
Run Code Online (Sandbox Code Playgroud)

然后entry在配置中使用变量。