我正在尝试为现有项目(节点应用程序)配置 Webpack。我面临多个问题,但无法解决其中任何一个,也不知道从哪里开始。
背景
这是项目的文件夹结构:
+---app
+---bin
+---public
| +---images
| +---javascripts
| +---stylesheets
+---resources
+---routes
+---test
+---utils
+---views
+---webpack.config.js
+---tsconfig.json
+---tsconfig.app.json
+---tsconfig.bin.json
+---tsconfig.public.json
+---tsconfig.routes.json
+---tsconfig.utils.json
+---jest.config.js
+---package.json
\---app.ts
入口文件为/bin/www.ts。它访问一个 Express API,其中有后端(应用程序文件夹)的路由和为前端提供服务的路由、位于视图文件夹中的 HTML 模板以及位于公共文件夹中的 JS 和 TS 文件。 TS 配置文件被划分为目标有时是 ES5,有时是 ES6。下面是 webpack 配置文件。
const path = require("path");
const { MiniHtmlWebpackPlugin } = require('mini-html-webpack-plugin')
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
module.exports = {
entry: {
main: path.resolve(__dirname, "bin/www.ts"),
},
output: {
filename: "projectname.bundle.js",
path: path.resolve(__dirname, "dist"),
},
// target: 'node',
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: "ts-loader",
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env']
}
}
},
],
},
devServer: {
static: "./dist",
port: 8080,
hot: true
},
resolve: {
extensions: [".ts", ".js"],
fallback: {
"querystring": require.resolve("querystring-es3"),
"timers": require.resolve("timers-browserify"),
"https": require.resolve("https-browserify"),
"path": require.resolve("path-browserify"),
"http": require.resolve("stream-http"),
"stream": require.resolve("stream-browserify"),
"crypto": require.resolve("crypto-browserify"),
"zlib": require.resolve("browserify-zlib"),
"os": require.resolve("os-browserify/browser")
// "fs": false,
// "tls": false,
// "stream": false,
// "crypto": false,
// "async_hooks": false,
}
// modules: ["node_modules"]
},
mode: "development",
plugins: [new MiniHtmlWebpackPlugin({ context: { title: "Project name" } })],
};
问题
当我尝试运行 webpack 时,出现此类错误:
ERROR in ./node_modules/multer/storage/disk.js 2:9-22
Module not found: Error: Can't resolve 'os' in 'C:\Users\**\**\**\node_modules\multer\storage'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
一共有 99 个。 我猜这是因为express应用程序使用节点模块,所以我尝试将目标设置为节点,但随后出现这种类型的警告:
WARNING in ./node_modules/express/lib/view.js 81:13-25
Critical dependency: the request of a dependency is an expression
或
WARNING in ./node_modules/mongodb/lib/encrypter.js 9:28-64
Module not found: Error: Can't resolve 'mongodb-client-encryption'
我认为这可能是因为我必须分开配置,但我不确定。我尝试了 StackOverflow 中的所有内容,包括 this one 和 this one 但没有任何效果。
我根本不是这种类型配置的专家,我尝试学习 webpack 但将其设置为现有项目,而且如此复杂的配置远远超出了我的处理能力,有人可以帮助我吗?
兄弟我能感受到你的痛苦。这是我的建议: 简化你的 webpack 配置文件以至少运行它。删除 webpack 配置文件中的所有内容(暂时),除了 mode、entry、output、target、externals... 加! 安装 webpack-node-externals 包并在配置文件中使用它,如下所示 这个链接