One of the things I find annoying when using import
in my JS code is the fact that you need to refer to other local files using (relative) paths. Like so:
// Without resolve.alias 😭
import Modal from '../../../components/objects/modal/modal';
Having a background in PHP – where you have include paths and autoloaders – I essentially want the code to know that all components can be found in src/ui/components
, allowing me to freely move files around without needing to update the paths of all import
statements.
Turns out Webpack allows one to do exactly just that, using resolve.alias
:
const webpackConfig = {
resolve: {
alias: {
Components: path.resolve(__dirname, 'src/components/'),
Containers: path.resolve(__dirname, 'src/containers/')
},
…
},
…
}
With resolve.alias
in place, imports can now be written as such, regardless of the location of the file importing it:
// With resolve.alias 😊
import Modal from 'Components/objects/modal/modal';
Aaah, much better 🙂
To not have to alias all folders, I’ve seen some people alias src/
to @
. That way they can import from @/Components/…
. Clever.
Consider donating.
I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!
Leave a comment