将 webpack 配置导出为函数失败

Exporting webpack config as a function fails

我正在尝试在我的 webpack 配置中处理开发和生产环境变量(参见 https://webpack.js.org/guides/production/),但它失败了

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'
    },
    // ...
}

此导出工作正常,没有错误或警告

module.exports = config; // everything is fine

但这失败了

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

    return config;
};

这里有一个类似但未回答的问题:webpack base config as a function doesn't work

这是一个非常神秘的行为,如果有人能提供帮助,我们将不胜感激!

嗯,它正在工作。我没有注意到错误发生在我的代码的完全不同的地方。

我正在用 webpack 和 express 做一个关于 HMR 的教程。导致问题的是快速设置中的这一行代码:

server.js

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

webpackConfig 只是获取一个函数而没有被调用,所以它没有返回一个对象。所以添加括号就可以让它工作了。

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

文档有点古怪。您正确地忘记了从 package.json

设置环境变量

例如 "start": "webpack --env.prod --", in package.json 将传递 {prod: true} 作为环境变量。

希望对您有所帮助。

更多信息在这里:https://webpack.js.org/api/cli/#environment-options