Skip to content

Latest commit

 

History

History
40 lines (30 loc) · 977 Bytes

better-module-imports-with-aliases.md

File metadata and controls

40 lines (30 loc) · 977 Bytes

Better Module Imports With Aliases

Depending on how your JavaScript project is structured, you can end up with import statements that look like this:

import SomeComponent from 'app/assets/javascripts/components/SomeComponent.jsx';

or this:

import SomeComponent from '../components/SomeComponent.jsx';

The first is simply too long and the second is both ugly and brittle to changes in file location. This can all be resolved with a Webpack alias.

// webpack.config.js
resolve: {
  alias: {
    components: "app/assets/javascripts/components",
  },
},

Webpack will use this alias when resolving module imports like the following updated example:

import SomeComponent from 'components/SomeComponent.jsx';

See the resolve.alias section of the Webpack docs for more details.

h/t Vidal Ekechukwu