Jide
Jide

Reputation: 1130

How to alias a relative path to a custom path using webpack?

A project uses a module A.

This module has requires with local paths, such as require('./otherModule').

How to make webpack resolve this path from another directory, and fallback to normal resolve if it does not exist ?

Upvotes: 9

Views: 5198

Answers (2)

Jide
Jide

Reputation: 1130

It's also possible to use NormalModuleReplacementPlugin like this :

  plugins: [
    new webpack.NormalModuleReplacementPlugin(/^\.\/ReactCompositeComponent$/, 'ReactCompositeComponent'),
    new webpack.NormalModuleReplacementPlugin(/^\.\/ReactDOMComponent$/, 'ReactDOMComponent')
  ]

Upvotes: 9

Johannes Ewald
Johannes Ewald

Reputation: 17805

There is no easy way to alias relative require() statements like require('./otherModule'). and I would not recommend to do this. It breaks with the fundamental concept of file paths and may confuse other programmers.

Root-relative paths (recommended)

You could use "root-relative" paths. These are paths that start with a /. Then you can write require statements like this require("/app/controller/otherModule.js"). You just need to tell webpack where your root is:

// webpack.config.js

module.exports = {
    ...
    resolve: {
        root: "/absolute/path/to/your/folder"
    }
    ...
};

You can also provide an array of paths to root.

Resolver plugin (not so recommended)

However, if you really need to alias these paths, you can hook in webpack's resolving mechanism. Webpack provides an extensive API for plugins to change its behavior. A plugin that rewrites all relative paths would look like this:

// webpack.config.js

var myWebpackPlugin = {
    apply: function (compiler) {
        compiler.resolvers.normal.apply(myResolverPlugin)
    }
};

var myResolverPlugin = {
    apply: function (resolver) {
        resolver.plugin("resolve", function (context, request) {
            if (request.path[0] === ".") {
                request.path = path.resolve(__dirname,
                    "whatever", "you", "like", request.path);
            }
        });
    }
}

module.exports = {
    ...
    plugins: [
        myWebpackPlugin
    ]
};

Upvotes: 9

Related Questions