我是 React 和 Webpack 的新手。我有webpack.config.js
像这样:
const webpack = require('webpack'); const 路径 = require('路径');
module.exports = {
cache: true,
entry: {
'user': ['./client/User/index']
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/static'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: path.join(__dirname, 'client'),
query: { cacheDirectory: true }
}
]
},
node: { fs: 'empty' }
};
这是我的 app.js
Express服务器入口:
import express from 'express';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import webpack from 'webpack';
import session from 'express-session';
const app = express();
import config from './webpack.config';
const compiler = webpack(config);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/assets', express.static(`${__dirname}/static`));
app.use('/', require('./server/route/index'));
app.listen(3000, () => console.log('Our Blog is listening on port 3000...'));
Webpack 不会在 dist
中构建并生成任何包。配置的文件夹。它只能在我使用 webpack-cli
时构建命令。另外,在我的html
文档中,我将 bundle 包含为 <script src='/static/user.bundle.js'></script>
。我想这一定是正确的路径,因为它将映射 /static
至dist
本地计算机上配置的文件夹,构建后 bundle 所在的位置。但由于找不到资源,它不断向我发送 404 错误。你能帮我解决这个问题吗?
最佳答案
webpack 在内存中创建文件。所以你看不到它 documentation .
webpack-dev-server doesn't write any output files after compiling. Instead, it keeps bundle files in memory and serves them as if they were real files mounted at the server's root path. If your page expects to find the bundle files on a different path, you can change this with the publicPath option in the dev server's configuration.
我怀疑是因为您没有将其指定为生产
模式,这就是它不写入dist
文件夹的原因。您还需要使用 webpack-dev-middleware 。这是 example为您介绍如何使用
我希望这会有所帮助。
关于javascript - 如何在 Express 服务器上启动 Webpack 构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57719394/