Improving your JavaScript codebase with one small change!

Tom Parsons
2 min readApr 10, 2022

Are you on a quest to improve your JavaScript syntax?
Want to make your code more consistent?
Are you tired of ugly import patterns like this littering your codebase?

Import Homer from "../../../../../../Components/Simpsons/Homer"
Import {Marge} from "../../../../../../Components/Simpsons"

When you could have something easier to add and easier to read instead?

Import Homer from "@Simpsons/Homer"
Import {Marge} from "@Simpsons"

This is called Module Resolution/Mapping, and thankfully it’s pretty simple to set up! The examples below have links to the docs if you’re interested in understanding it further.

Getting started

Depending on your tools you may need different/specific configurations, but here are the basics:

Typescript, Next & Angular

File: tsconfig.json (or whatever you use for your TS Config)
Typescript Docs: link
Next Docs: link
Angular Docs: link

{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@Simpsons/*": ["/path/to/Components/Simpsons/*"]
}
}
}

Jest

File: .jest.config
Docs: link

moduleNameMapper: {
// existing module maps
"^@Simpsons/(.*)$": "<rootDir>/path/to/Components/Simpsons/$1"
}

Gatsby

Addon: gatsby-plugin-root-import (npm)
File: gatsby-config.js
Docs: link

{
resolve: "gatsby-plugin-root-import",
options: {
"@Simpsons": '/path/to/Components/Simpsons'
}
}

Webpack

File: webpack.config.js
Docs: link

module.exports = {
resolve: {
alias: {
"@Simpsons": path.resolve(__dirname, "/path/to/Components/Simpsons"),
},
},
};

Storybook

Update:

Storybook has now included this in their documentation

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
webpackFinal: async (config) => {
config.resolve.plugins = [
...(config.resolve.plugins || []),
new TsconfigPathsPlugin({
extensions: config.resolve.extensions,
}),
];
return config;
},
};

Before:

File: main.js — NB: this is part of the Webpack config for Storybook and the docs are the same as above
Docs: link (for storybook and Webpack)

module.exports = {
webpackFinal: async (config, { configType }) => {
config.resolve.alias = {
...config.resolve.alias,
"@Simpsons": path.resolve(__dirname, "/path/to/Components/Simpsons"),
};
return config;
},
};

Your configs may need some tweaking from the above, but hopefully, this gets you going in the right direction!

--

--

Tom Parsons

Front End person, you can find me on github @thomasparsons