通过要求的WebPack动态模块加载

问题描述 投票:6回答:3

OK,我已搜查高和低,但不能可靠地确定这是否是或不是可能的的WebPack。

https://github.com/webpack/webpack/tree/master/examples/require.context似乎表明,人们可以通过一个字符串的函数,它加载模块...

但我的尝试只是不工作: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 );
});

在模块/命名test.js模块

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

但结果总是一样的... PM2日志只是打个招呼世界的静态需要,而是为了同一个模块的动态负载

错误:无法找到模块“”

所有我希望能够做的是通过的路径的阵列模块和负载然后循环...

javascript node.js webpack require webpack-2
3个回答
34
投票

你不能使用一个变量作为参数传递给require。的WebPack需要知道哪些文件在编译时捆绑。因为它没有程序流分析,就不能知道你传递给函数的。在这种情况下,它可能是显而易见的,但是这可能会去尽可能使用用户输入来决定需要哪些模块,并没有的WebPack没有办法可以大概知道哪些模块在编译时包括这样的WebPack不允许它。

您发布的例子是有点不同。你可以使用require有一个连接字符串。例如:

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

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

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

所有这些test.js文件将被包含在捆绑,因为moduleName可能是one什么样的嵌套two/subdir

欲了解更多详情,请参阅require with expression的官方文档中。

无法通过的阵列循环并导入所述阵列的每一个模块,通过连接字符串上述异常,但具有包括所有可能的模块和一般应避免的效果。


6
投票

我遇到了在电子环境下这个问题。我使用的案件能够像应用程序的IDE来require动态创建的文件。我想用电子require,这基本上是一个常见的NodeJS模块加载器。一些来回后,我降落在使用的WebPack的noParse模块配置的解决方案。

首先创建一个将通过的WebPack的解析器忽略一个模块:

// file: native-require.js
// webpack replaces calls to `require()` from within a bundle. This module
// is not parsed by webpack and exports the real `require`
// NOTE: since the module is unparsed, do not use es6 exports
module.exports = require

在我的WebPack配置,下module,指导捆绑不来解析这个模块:

{
  module: {
    noParse: /\/native-require.js$/,
  }
}

最后,要访问原始要求任何捆绑:

import nativeRequire from './native-require`
const someModule = nativeRequire('/some/module.js') // dynamic imports

1
投票

有点晚了....但是...因为要捆绑到target: 'node',有一种变通方法,以动态的,需要的模块,并绕过“包括所有可能模块的作用”。

该解决方案是从提升:

Using dynamic require on node targets WITHOUT resolve or bundle the target module · Issue #4175 · webpack/webpack

从评论行情:

const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
const foo = requireFunc(moduleName);

捆绑:

const requireFunc = true ? require : require;
const foo = requireFunc(moduleName);
© www.soinside.com 2019 - 2024. All rights reserved.