webpack 动态模块加载器按要求 [英] webpack dynamic module loader by require

查看:23
本文介绍了webpack 动态模块加载器按要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经搜索了高低,但无法可靠地确定 webpack 是否可行.

OK, i have searched high and low but cannot reliably deterrmine if this is or is not possible with webpack.

https://github.com/webpack/webpack/tree/主/示例/require.context似乎表示可以将字符串传递给函数并加载模块...

https://github.com/webpack/webpack/tree/master/examples/require.context Appears to indicate that one can pass a string to a function and it load a module...

但我的尝试不起作用:webpack.config.js

But my attempt is just not working: webpack.config.js

'use strict';
let webpack     = require('webpack'),
    jsonLoader  = require("json-loader"),
    path        = require("path"),
    fs          = require('fs'),
    nodeModules = {};

fs.readdirSync('node_modules')
    .filter(function(x) {
        return ['.bin'].indexOf(x) === -1;
    })
    .forEach(function(mod) {
        nodeModules[mod] = 'commonjs ' + mod;
    });


let PATHS = {
    app: __dirname + '/src'
};

module.exports = {
    context: PATHS.app,
    entry: {
        app: PATHS.app+'/server.js'
    },
    target: 'node',
    output: {
        path: PATHS.app,
        filename: '../build/server.js'
    },
    externals: nodeModules,
    performance: {
        hints: "warning"
    },
    plugins: [
        jsonLoader
    ],
    resolve: {
        modules: [
            './node_modules',
            path.resolve(__dirname),
            path.resolve(__dirname + "/src"),
            path.resolve('./config')
        ]
    },
    node: {
        fs: "empty"
    }
};

server.js

let _ = require('lodash');
let modules = [ "modules/test" ];

require( 'modules/test' )();

_.map( modules, function( module ){
    require( module );
});

modules/中的模块名为 test.js

The module in modules/ named test.js

module.exports = () => {
    console.log('hello world');
};

但结果总是一样的... pm2 日志只是对静态要求说 hello world... 但是对于同一模块的动态加载

But the result is always the same... the pm2 logs just say hello world for the static require... but for the dynamic load of the same module

错误:找不到模块."

我想要做的就是遍历模块路径数组,然后加载...

All i want to be able to do is loop through an array of paths to modules and load then...

推荐答案

不能使用变量作为 require 的参数.Webpack 需要知道在编译时捆绑哪些文件.由于它不进行程序流分析,因此无法知道您传递给函数的内容.在那种情况下它可能很明显,但是这可能会使用用户输入来决定需要哪个模块,并且 webpack 不可能知道在编译时包含哪些模块,因此 webpack 不允许这样做.

You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time. As it does no program flow analysis, it can't know what you pass to the function. In that case it might be obvious, but this could go as far as using user input to decide what module to require, and there is no way webpack can possibly know which modules to include at compile time, so webpack does not allow it.

您发布的示例有点不同.您可以将 require 与连接的字符串一起使用.例如:

The example you posted is a bit different. You could use require with a concatenated string. For example:

require(`./src/${moduleName}/test`);

webpack 需要在 bundle 中包含哪些模块?变量 moduleName 可以是任何东西,所以在编译时不知道确切的模块.相反,它包括可能与上述表达式匹配的所有 模块.假设目录结构如下:

Which modules does webpack need to include in the bundle? The variable moduleName could be anything, so the exact module is not known at compile time. Instead it includes all modules that could possibly match the above expression. Assuming the following directory structure:

src
├─ one
│   └─ test.js
├─ two
│   ├─ subdir
│   │   └─ test.js
│   └─ test.js
└─ three
    └─ test.js

所有这些 test.js 文件都将包含在包中,因为 moduleName 可以是 one 或嵌套的类似 二/子目录.

All of these test.js files will be included in the bundle, because moduleName could be one or something nested like two/subdir.

更多细节参见require with expression官方文档.

For more details see require with expression of the official docs.

您不能循环遍历数组并导入数组的每个模块,除了上述通过连接字符串的例外,但这会导致包含所有可能的模块,通常应避免.

You cannot loop through an array and import every module of the array, with the above exception by concatenating a string, but that has the effect of including all possible modules and should generally be avoided.

这篇关于webpack 动态模块加载器按要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆