webpack-4dev-to-production

Exporting webpack config as a function fails


I'am trying to handle development and production eviroment variables in my webpack configuration (see https://webpack.js.org/guides/production/), but it fails with

WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration should be an object.

package.json

        {
          "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1",
            "build": "./node_modules/.bin/webpack",
            "start": "npm run build && node server.js"
          },
          "devDependencies": {
             //...
             "webpack": "^4.20.2",
             "webpack-cli": "^3.1.2",
             "webpack-dev-middleware": "^3.4.0",
             "webpack-hot-middleware": "^2.24.2"
          }
       }

webpack.config.js

const path = require('path'),
    webpack = require('webpack'),
    HtmlWebpackPlugin = require('html-webpack-plugin');

let config = {
    entry: {
        app: [
            './src/app/App.tsx', 'webpack-hot-middleware/client'
        ],
        vendor: ['react', 'react-dom']
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].bundle.js'
    },
    // ...
}

This export is working as expected without errors or warnings

module.exports = config; // everything is fine

But this fails

module.exports = function(env, argv) { // this errors

    return config;
};

There is a similiar, but unanswered question here: webpack base config as a function doesn't work

It's a very mysterious behaviour, appreciate if anyone could help!


Solution

  • Well,it is working. I didn't notice that the error takes place on a total different spot of my code.

    I was doing a tutorial about HMR with webpack and express. An it's this lines of code in the express setup which causes the trouble:

    server.js

    const webpackConfig = require('./webpack.config');
    const compiler = webpack(webpackConfig);
    //...
    app.use(
        require('webpack-dev-middleware')(compiler, {
            noInfo: true,
            publicPath: webpackConfig.output.publicPath
        })
    );
    

    The webpackConfig is only getting a function without being called and so it's not returning an object. So adding parenthesis is all it took to make it work.

    const webpackConfig = require('./webpack.config')();
    //..