necroface
necroface

Reputation: 3465

How to make Webpack build on Express server started

I'm new to React and Webpack. I have webpack.config.js like this:

const webpack = require('webpack'); const path = require('path');

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' }
};

And this is my app.js entry of Express server:

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 does not build and yields any bundle in the dist folder as configured. It can only build when I use webpack-cli command. Besides, in my html document, I include the bundle as <script src='/static/user.bundle.js'></script>. I thought this must be the correct path, because it will map /static to dist folder on local machine as configured where the bundle is exactly located after build. But it keeps sending me 404 error due to resource not found. May you help me solve this?

Upvotes: 0

Views: 441

Answers (1)

Jasper Bernales
Jasper Bernales

Reputation: 1681

webpack creates the file in memory. so you can't see it as per 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.

I suspect because you did not specify it as production mode that's why it's not writing to dist folder. Also you need to use webpack-dev-middleware. Here's an example for you how to use it

I hope this helps.

Upvotes: 1

Related Questions