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

标签 javascript webpack

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

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/

相关文章:

javascript - 如何触发回车键

javascript - 使用 webpack 在浏览器中使用 require 模块

javascript - 不确定为什么 res.send 不将我的对象发送到前端

css - Webpack 和字体 : module parse failed

javascript - 如何删除从特定加载文件生成的所有事件监听器?

javascript - 带有 .play() 的动态声音文件

javascript - d3.js x 轴上的缩放时间不起作用

javascript - jquery.mockjax 与需要 shim 的 Webpack 一起使用

reactjs - 我正在尝试建立一个新的react.js项目并出现编译错误

javascript - require() 一个 node.js 模块?