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 ?
React emphasises on modular code and component architecture. Dividing the app into presentational and container components makes the code more readable and also reusable.
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.
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.
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
.
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
]
};
It's also possible to use NormalModuleReplacementPlugin like this :
plugins: [
new webpack.NormalModuleReplacementPlugin(/^\.\/ReactCompositeComponent$/, 'ReactCompositeComponent'),
new webpack.NormalModuleReplacementPlugin(/^\.\/ReactDOMComponent$/, 'ReactDOMComponent')
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With