Absolute paths for webpack
abspath-webpack-plugin
is a custom absolute path(s) provider for your webpack builds.
It helps you get rid of relative paths in your require
s and import
s.
To install the latest stable version:
npm install --save-dev abspath-webpack-plugin
This assumes you are using npm as your package manager. The abspath-webpack-plugin
requires webpack
as peerDependency
. Thus you are able to specify the required versions accurately.
new AbsolutePathProviderPlugin(newRegEx, absolutePath);
newRegEx
is the regular expression to be matched in the require
d path and gets replaced with the absolutePath
provided as the second argument.
You can also append path to the regex in your require
statement. It automatically gets appended to the absolutePath
.
You need to use abspath-webpack-plugin
with other plugins in your webpack configuration.
var webpack = require('webpack');
var AbsolutePathProviderPlugin = require('abspath-webpack-plugin');
module.exports = {
plugins: [
new AbsolutePathProviderPlugin(
/* regex */: /* absolute path to some dir */
)
]
}
Let's see how can we use the plugin to simplify our require
statements.
Here is your simple app structure, let's say.
app/
+-- _webpack.config.js
+-- scripts/
+-- accounts/
+-- signup/
+-- app.js
+-- components/
+-- modal/
+-- index.js
+-- modal.js
+-- message/
+-- index.js
+-- message.js
Now you need to use your modal and message components in scripts/accounts/signup/app.js
. The usual way would be
var modal = require('./../../../components/modal');
var message = require('./../../../components/message');
That's not very efficient, right? Let's put abspath-webpack-plugin
into play.
var path = require('path');
var webpack = require('webpack');
var AbsolutePathProviderPlugin = require('abspath-webpack-plugin');
module.exports = {
plugins: [
new AbsolutePathProviderPlugin(
/^@components/: path.resolve('./components')
)
]
}
var modal = require('@components/modal');
var message = require('@components/message');
Or if you're using ES2015 syntax,
import modal from '@components/modal'
import message from '@components/message'
We are open to, and grateful for, any contributions made by the community. You can contribute by:
- Reporting a bug.
- Suggesting a feature.
- Opening an issue to discuss improvements, theory or implementation.
If you are opening a PR, please attach the relevant issue with it. If it doesn't exist, please create one before you open a PR.
MIT