gpt4 book ai didi

javascript - 如何在 Express 服务器上启动 Webpack 构建

转载 作者:行者123 更新时间:2023-12-02 23:02:47 25 4
gpt4 key购买 nike

我是 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> 。我想这一定是正确的路径,因为它将映射 /staticdist本地计算机上配置的文件夹,构建后 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com