如何在项目之间共享webpack.config片段?

时间:2017-07-17 12:56:40

标签: npm webpack-2

我有几个webpack配置与非常相似的webpack.config文件。我喜欢把webpack.config部分放在一个共享模块中(我用“npm link”包含共享模块),但这不起作用,因为找不到依赖项,比如“webpack”,因为它是它遇到的第一个依赖项

17 07 2017 14:49:32.694:ERROR [config]: Invalid config file!
  Error: Cannot find module 'webpack'
    at Function.Module._resolveFilename (module.js:470:15)

首先是webpack.config行:

const webpack = require('webpack');
const path = require('path');
....

如何指示webpack在包含webpack.config的项目的node_modules中搜索包含的依赖项?

我尝试通过在解析webpack.config部分添加以下内容来实现这一点,但这没有帮助:

  

modules:[path.resolve(__ dirname,“node_modules”),“node_modules”]

我认为它不是由webpack.config本身使用的,而是由webpack.config处理的JS代码使用。

1 个答案:

答案 0 :(得分:0)

我通过将所需的根目录作为参数传递给公共webpack配置来解决它,并使用它来更改用于查找插件和其他东西的__dirname变量。

在代码中: webpack.config.js:

const path = require('path');
const loader = require('lodash/fp');
const common = require('bdh-common-js/etc/webpack/webpack.config.common');

module.exports = function (env) {
    if (env === undefined) {
        env = {};
    }
    env.rootdir = __dirname; // Add the root dir that can be used by the included webpack config.

    const result = loader.compose(
        function () {
            return common(env)
        }
        // Any other "fragments" go here.
    )();

    // Customize the webpack config:
    result.entry = {
        entry: ['./src/entry.js', './src/js/utils.js'],
    }
    result.resolve.alias.Context = path.resolve(__dirname, 'src/js/context');
    ...... more stuff..
    return result;
}

接收参数的常见webpack.config部分:

module.exports = function (env) { 
    if (env !== undefined) {
        if (env.rootdir !== undefined) {
            __dirname = env.rootdir;
        }
    }
  ....
    const node_modules = path.resolve(__dirname, 'node_modules');
    const webpack = require(node_modules + '/webpack');
    const CleanWebpackPlugin = require(node_modules + '/clean-webpack-plugin');
 ....

}