Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 499
Jide Avatar asked Feb 13 '16 16:02

Jide


People also ask

How can webpack help you avoid relative path imports?

React emphasises on modular code and component architecture. Dividing the app into presentational and container components makes the code more readable and also reusable.

What is relative path in API?

A Relative Path binds policies to a specific relative path location (for example /test/path ). When the API Gateway receives a request on the specified Relative Path, it invokes the specified policy or policy chain.


2 Answers

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
    ]
};
like image 133
Johannes Ewald Avatar answered Sep 21 '22 14:09

Johannes Ewald


It's also possible to use NormalModuleReplacementPlugin like this :

  plugins: [
    new webpack.NormalModuleReplacementPlugin(/^\.\/ReactCompositeComponent$/, 'ReactCompositeComponent'),
    new webpack.NormalModuleReplacementPlugin(/^\.\/ReactDOMComponent$/, 'ReactDOMComponent')
  ]
like image 33
Jide Avatar answered Sep 19 '22 14:09

Jide