将参数传递给基本Webpack配置

时间:2018-10-01 15:49:04

标签: typescript webpack

我们正在尝试使用基本配置和多个条目配置来设置Webpack。使用基本功能几乎可以完成所有工作,但根据构建目标还可以包含一些其他文件。我们的基本设置如下:

const webpack = require("webpack");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = (env) => {
    return {
        entry: {
            ...
        },
        output: {
            ...
        },
        optimization: {
            ...
        },
        module: {
            ...
        },
        resolve: {
            ...
        },
        plugins: [
            ...
        ]
    };
};

条目配置如下:

const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');

module.exports = (env) => {    
    return merge(common(env), {
        mode: 'production',
        plugins: [
            ...
        ]
    });
}

这在我的机器上工作正常,但是当其他人运行它时,他们得到:

  

TypeError:常见的不是函数

这是将选项传递到入口和基本Webpack文件的最佳方法吗?这一切似乎都可以在本地正常运行,并且可以正确构建所有内容并运行。我们使用webpack.DefinePlugin使传入的条目在javascript应用程序中可用。

2 个答案:

答案 0 :(得分:0)

在删除存储库时,只需发布​​最小的repro设置以供将来参考(对我来说效果很好)。问题是合并问题,与webpack无关。

// file: src/hello-world.js
module.exports = () => {
    console.log("Hello, world!");
}

// file: src/index.js
const helloWorld = require('./hello-world');
helloWorld();

// file: webpack.common.js
module.exports = (env) => {
    console.log("./webpack.common: " + env + " was passed for argument 'env'.");
    return {
        mode: env
    }    
};

// file: webpack.config.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.common');

module.exports = (env) => {
    return merge(common(env), {});
};

// file: package.json
{
  "name": "webpack-param-repro",
  "version": "1.0.0",
  "description": "A minimal app to reproduce the problem in https://stackoverflow.com/q/52594681/824495",
  "main": "dist/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Mehmet Seckin",
  "repository": {
    "type": "git",
    "url": "https://github.com/seckin92/webpack-param-repro"
  },
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.2",
    "webpack-merge": "^4.1.4"
  }
}

答案 1 :(得分:0)

这里是一个不错的替代解决方案webpack-merge。不要重新发明轮子。它已经存在了:)