node.js - 将 Node.js 服务器与 Webpack 捆绑时找不到 index.html
问题描述
我正在尝试设置 webpack 来捆绑我的后端代码。
我的 webpack 配置如下所示:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const outputDirectory = 'dist';
const client = {
mode: 'production',
entry: {
'app': [
'babel-polyfill',
'./client/index.js'
]
},
output: {
path: path.join(__dirname, outputDirectory),
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader'
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(gif|svg|jpg|png)$/,
loader: "file-loader"
}
]
},
plugins: [
new CleanWebpackPlugin([outputDirectory]),
new HtmlWebpackPlugin({
template: './index.html',
})
]
}
const server = {
mode: 'production',
target: 'node',
entry: {
'app': [
'./server/server.js'
]
},
externals: [nodeExternals()],
output: {
path: path.join(__dirname, '/server'),
filename: 'server.bundle.js'
}
}
module.exports = [client, server]
如果我运行非 webpack server.js,一切正常。但是,如果我运行 webpack 捆绑的 server.bundle.js,快递会抛出:
Error: ENOENT: no such file or directory, stat '/dist/index.html'
两个服务器文件都在同一个目录中。有没有人遇到过这个问题?
解决方案
我想通了,它没有在 webpack 的文档中明确说明,但是你需要在使用 express 时配置一个“节点”属性
前任。将此添加到您的配置中
node: {
// Need this when working with express, otherwise the build fails
__dirname: false, // if you don't put this is, __dirname
__filename: false, // and __filename return blank or /
},
推荐阅读
- sql - 如何使用 SQL 拆分两个单词?
- terraform - 带有工作区的数据源 terraform_remote_state
- amazon-web-services - S3用自定义错误替换默认xml错误不起作用
- c# - 根据属性名称更改对象属性的值
- java - nonProxyHosts 的有效模式是什么?只希望来自一台主机的请求通过代理。如何排除所有其他主机?
- python - 时间数据“2021 年 5 月 10 日”与格式“%m %d %Y”不匹配
- jboss - 安装服务以仅在集群内的 Slave/Worker 节点节点上运行 - Jboss Application Server
- python - 为什么要获取 django.core.exceptions.AppRegistryNotReady:应用程序尚未加载。在创建 CustomUser 和 CustomUserManager
- python - 如何将具有多级列和轴名称的数据透视表转换为行?
- python - /blog/ 处的 DatabaseError 未提供异常消息