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

标签 javascript node.js reactjs express webpack

我是 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/

相关文章:

javascript - Nodejs - 无法读取文件目录中有空间的文本文件

node.js - Nodejs解构require

javascript - 下次访问时恢复动态内容中的阅读位置

javascript - 清除 React 组件中来自父级或祖级组件的输入

javascript - 解析: count of objects with pointer to another type object with given ID

javascript - 事件中的 someFunction() 和 someFunction 有什么区别?

javascript - Angular ng-repeat <li> 字符串换行

用于监控网络请求和响应的 Node.js 代理

node.js - $sort 使聚合管道 mongodb 中的 $skip 无效

javascript - 如何在 javascript 中定义模块的导出?