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

问题描述 投票:0回答:1

我有几个带有非常相似的

webpack.config
文件的 webpack 配置。我喜欢将
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代码使用。

npm webpack-2
1个回答
2
投票

我通过将所需的根目录作为参数传递给常见的 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');
 ....

}
© www.soinside.com 2019 - 2024. All rights reserved.