How to alias relative path to custom path using webpack?

The project uses module A.

This module requires local paths, for example require('./otherModule').

How to force webpack to resolve this path from another directory and return to normal resolution if it does not exist?

+4
source share
2 answers

There is no easy way to describe relative expressions require()like this require('./otherModule')., and I would not recommend doing this. It breaks down with the fundamental concept of file paths and can confuse other programmers.

Root relative paths (recommended)

"" . , /. require("/app/controller/otherModule.js"). webpack, root:

// webpack.config.js

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

root.

Resolver ( )

, , webpack. Webpack API , . , , :

// 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
    ]
};
+5

NormalModuleReplacementPlugin :

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

Source: https://habr.com/ru/post/1628644/


All Articles