【发布时间】:2021-10-08 20:53:08
【问题描述】:
我在为我的 ssr react 服务器设置 webpack 时遇到了困难。我在这里阅读了有关 stackoverflow 的几篇文章,其他文章并没有任何效果。问题与 webpack-node-externals 包有关。我尝试了几种配置:
- 没有 nodeExternals:我的应用程序抛出错误“process.hrtime”不是函数
- 使用 nodeExternals:我的包缺少 mypackage.json 中列出的依赖项(压缩等)。这是因为它让 require('moduleName') 无处不在,很明显
- nodeExternals 和 options.modulesFromFile 参数设置为
modulesFromFile: {
fileName: path.resolve(__dirname),
includeInBundle: ['dependencies']
}
我在这里遇到了来自用户代理模块(未在我的部门中列出)“找不到模块请求”的错误。当我手动安装请求时,还有其他我现在不记得的错误。
最后我不知道我做错了什么。这是我的 webpack 配置文件的示例:
const path = require('path');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const {
BundleAnalyzerPlugin
} = require('webpack-bundle-analyzer');
const IS_PRODUCTION = process.env.MODE === 'production';
const config = {
entry: path.resolve(__dirname, 'src/server/index.ts'),
mode: IS_PRODUCTION ? 'production' : 'development',
output: {
path: path.resolve(__dirname, 'dist/server'),
publicPath: IS_PRODUCTION ? 'dist/' : undefined,
filename: 'index.js',
},
externals: [nodeExternals()],
resolve: {
extensions: ['.js', '.ts', '.tsx', '.json'],
fallback: {
fs: false,
yamlparser: false,
tls: false,
net: false,
},
},
target: 'node',
module: {
rules: [{
test: /\.((t|j)s(x?))$/u,
exclude: /node_modules/,
use: {
loader: 'swc-loader',
},
},
{
test: /\.(ts|tsx)$/u,
exclude: /node_modules/,
loader: 'ts-loader',
options: {
configFile: path.resolve(__dirname, 'tsconfig.webpack.json'),
},
},
{
test: /\.(png|jpg|jpeg|ico)$/u,
exclude: /node_modules/,
loader: 'file-loader',
},
],
},
plugins: [new NodePolyfillPlugin(), new CleanWebpackPlugin()],
};
if (IS_PRODUCTION) {
config.optimization = {
minimize: true,
};
}
if (process.env.BUNDLE_ANALYZER === 'true') {
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'bundle-report-server.html',
})
);
}
module.exports = config;
【问题讨论】:
标签: node.js reactjs typescript webpack server-side-rendering