好的,我已经反复搜索过了,但是无法可靠地确定是否可以使用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"
}
};
服务器.js
let _ = require('lodash');
let modules = [ "modules/test" ];
require( 'modules/test' )();
_.map( modules, function( module ){
require( module );
});
位于modules/目录下名为test.js的模块
module.exports = () => {
console.log('hello world');
};
但结果总是相同的... pm2日志仅显示静态require的“hello world”... 但对于相同模块的动态加载
错误:找不到模块“。”
我想做的就是循环遍历模块路径数组并加载它们...
require('./src/' + moduleName );
。请阅读附加的带表达式的require文档。 - niranjan_harpale