Introduction
Sometimes, when working with JavaScript and module bundlers, it’s useful to create aliases in order to import
or require
some modules more easily. In Webpack for example you can use the resolve.alias
directive inside the configuration file.
module.exports = {
//...
resolve: {
alias: {
'applicationRoot': path.resolve(__dirname, 'src/')
}
}
};
A common use case for aliases is to abstract the application root, so instead of using relative paths when importing like so:
import MyModule from '../../../nested/module';
you can use the alias:
import Utility from 'applicationRoot/nested/module';
Notice
an established convention is to use the @
sign in path to refer to the application root. See this SO answer
Rollup.js
Rollup.js is a nice alternative to Webpack. It has similar API, but it is more lightweight and it feels simpler at a first glance. The debate if you should use one or the other is still going on as today, but the convention says that you should use Webpack for apps and Rollup for libraries. Rollup also added code splitting recently, which was the major lacking feature compared to Webpack.
Rollup does not provide the ability to alias modules on its own, but you need to add the rollup-plugin-alias plugin.
// rollup.config.js
import alias from 'rollup-plugin-alias';
export default {
input: './src/index.js',
plugins: [alias({
applicationRoot: __dirname + '/src'
})],
}
Using this simple configuration you can abstract applicationRoot
to be the root of your application and require modules from there.
Bonus: Jest
If you are using Jest as your testing framework you also need to instruct it how to interpret applicationRoot
otherwise it would just fail when running the test suite. Luckily for us the Jest configuration offers the moduleNameMapper
option which maps from regular expressions to module names. We can define our mapping between applicationRoot
and the application source root by using the <rootDir>
string token.
module.exports = {
// A map from regular expressions to module names that allow to stub out resources with a single module
moduleNameMapper: {
"^applicationRoot/(.*)$": "<rootDir>/src/$1",
}
}
Happy bundling!