How can I share webpack.config snippets between projects?

谁都会走 提交于 2019-12-11 02:35:52

问题


I have several webpack configurations with very similar webpack.config files. I like to put webpack.config parts in a shared module that (I include the shared module with "npm link"), but that doesn't work as can't find dependencies, like "webpack" as it's the first dependency it encounters.

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)

First webpack.config lines:

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

How can I instruct webpack to search for the included dependences in node_modules of the project that includes the webpack.config?

I tried to realise this by adding the following to the resolve webpack.config section, but that doesn't help:

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

I think it's not used by the webpack.config itself but by the JS code that is processed by webpack.config.


回答1:


I solved it by passing in required root dir as argument to the common webpack config, and use that to change the __dirname variable that is used to find plugins and other stuff.

In code: The 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;
}

And the common webpack.config part that receives the argument:

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');
 ....

}


来源:https://stackoverflow.com/questions/45144918/how-can-i-share-webpack-config-snippets-between-projects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!