webpackwebpack-dev-middlewarewebpack-hot-middleware

Webpack5 prevent fallback packages from being resolved when config is required in application


In Webpack 5, polyfill of core node modules are removed, instead required packages are required to listed in resolve.fallback property. Below is resolve property of webpack.config.client.js file.

resolve: {
  fallback: {
    path: require.resolve("path-browserify"),
    crypto: require.resolve("crypto-browserify"),
    "babel-polyfill": require.resolve("@babel/polyfill"),
    buffer: require.resolve("buffer/"),
    stream: require.resolve("stream-browserify"),
  }
}

I use webpack-dev-middleware and webpack-hot-middleware along with express to achieve benefit of HMR for my ssr application.

import express from "express";
import webpack from "webpack";
...
const app = express();
...
const webpackDevConfig = require("../webpack/webpack.config.client");
const compiler = webpack(webpackDevConfig);
app.use(
  require("webpack-dev-middleware")(compiler, {
    publicPath: webpackDevConfig.output.publicPath,
  }),
);
app.use(require("webpack-hot-middleware")(compiler));
...

When the config file is imported, those modules in fallback property are resolved and returned as number. And webpack throws an error when the config object is passed to its constructor since configuration.resolve.fallback property should be non empty string, but numbers were given.

Below is the actual resolve.fallback property passed, and the error returned.

{
  path: 79936 (which suppose to be "/some path/node_module/path/index.js",
  crypto: 32640,
  'babel-polyfill': 71202,
  buffer: 30816,
  stream: 78787
}

ValidationError: Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.resolve.fallback should be one of these:
   [object { alias, name, onlyModule? }, ...] | object { <key>: [non-empty string, ...] | false | non-empty string }
   -> Redirect module requests. 
.....

Solution

  • Use Webpack Magic Comment, then webpack won't bundle the imported libraries.

    const webpackDevConfig = require(/* webpackIgnore: true */ "../webpack/webpack.config.client");