将Webpack配置导出为功能失败

时间:2018-10-01 15:18:02

标签: webpack-4 dev-to-production

我正在尝试在我的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

这是一个非常神秘的行为,如果有人能帮忙,请多谢!

2 个答案:

答案 0 :(得分:0)

好,它正在工作。我没有注意到该错误发生在我的代码的不同位置。 我当时正在使用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')();
//..

答案 1 :(得分:0)

文档有点古怪。您正确地从package.json中忘记了设置env变量

例如,package.json中的"start": "webpack --env.prod --",将通过{prod:true}作为env变量。

希望这会有所帮助。

此处有更多信息:https://webpack.js.org/api/cli/#environment-options