npmwebpack-2

How can I share webpack.config snippets between projects?


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 dependencies 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.


Solution

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