【问题标题】:How can I share webpack.config snippets between projects?如何在项目之间共享 webpack.config 片段?
【发布时间】:2017-07-17 12:56:39
【问题描述】:

我有几个 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 中搜索包含的依赖项?

我试图通过将以下内容添加到 resolve webpack.config 部分来实现这一点,但这无济于事:

模块:[path.resolve(__dirname, "node_modules"), "node_modules"]

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

【问题讨论】:

  • 你有没有找到解决方案,我也有同样的要求,我一直在四处寻找,几乎一无所获
  • 是的,我在 2 周前就是这样做的,忘记在这里回答了,我现在就回答。

标签: npm webpack-2


【解决方案1】:

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

}

【讨论】:

  • 覆盖__dirname 确实有帮助。谢谢!
猜你喜欢
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
相关资源
最近更新 更多