我正在使用Webpack(4.43.0)为AWS Lambda编码拆分一个NodeJS应用程序。我有一个 main
bundle,它很小,包含了我写的代码,而且我有一个 vendors
bundle,它很大,包含了所有(树形摇动)node_modules的依赖关系,比如Express.JS。问题是,当我运行主块时(用 node ./dist/main.js
)中的依赖关系,它无法解决在 vendors
bundle。通过阅读输出代码,我看不出它是如何解决的。vendors
模块作为 main
并没有办法解决它们。
我收到的错误是
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
TypeError: Cannot read property 'call' of undefined
读取代码输出时 dist/main.js
Webpack bootstrap函数接收以下模块列表。
[
'./node_modules/express/lib sync recursive',
'./src/main.ts',
'buffer',
'crypto',
'events',
'fs',
'http',
'net',
'path',
'querystring',
'stream',
'string_decoder',
'tty',
'url',
'util',
'zlib'
]
列表中的 ./src/main.ts
为切入点,并在此执行。
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/main.ts");
这个模块试图包含 ./node_modules/express/index.js
这就会抛出错误,因为它不存在于初始模块列表中。
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
如果我手动注入下面的代码,将 "供应商 "模块导入到模块列表中,代码就会正常工作,但这不是一个理想的解决方案。
const vendor = require('./vendors~main.js');
Object.keys(vendor.modules).forEach((mod) => {
modules[mod] = vendor.modules[mod];
});
有谁知道让 "供应商 "模块可用的正确方法吗?
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
target: 'node',
entry: './src/main.ts',
output: {
path: path.join(__dirname, './dist'),
filename: '[name].js',
libraryTarget: 'commonjs',
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
module: {
rules: [
{ test: /\.ts$/, use: 'ts-loader' }
]
},
optimization: {
sideEffects: false,
namedModules: true,
namedChunks: true,
splitChunks: {
chunks: 'all'
}
},
};
main.ts
import express from 'express';
const port = 3000;
const app = express();
app.get('*', (req: express.Request, res: express.Response) => {
res.send('Working');
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
我设置了一个演示版本 https:/github.comrjenkinnodejscodesplit。
显然target: "node "不支持 splitChunks with chunks: "initial "或chunks: "all"。https:/github.comwebpackwebpackissues7392