DEV Community

Cover image for Javascript module imports in large projects
Mrinal Raj
Mrinal Raj

Posted on

3

Javascript module imports in large projects

We all have been there, starting off a new project and writing long relative paths as we go ignoring all the trouble it can cause later.

But let us forget about all the upcoming troubles for a while and assume we will never reach past 15 files in the whole project. Do you actually like writing those dots and slashes? Do the unstructured codes never bother you? Has it never happened that it’s the middle of the night and you those ../../../../../../ scare the hell out of you? Anyways, let's see the actual problem.

The problem

As you keep on scaling your project past a certain point of complexity, you’ll end up traversing up and down your directory structures. Which is first of all time-consuming and error-prone as well as absence of an IDE can make it a nightmare to remember all directory and files. Even with code-completion features like IntelliSense in place (supported by almost every IDE), this can become more challenging as your codebase grows.

import variables from '../../../../varibles'
import { module } from '../module-parent/module-itself'
import getLocation from '../../../../utils/location-services/location-reciever'
const location = getLocation()
// can these imports be somehow simplified

Just imagine a situation where you are changing the directory structure of a module in your project. This will break all the module references and you will be forced to change all occurrences of the module throughout your project. It will be a daunting task!

The Solution

Webpack allows you to create aliases to import or require certain modules through the resolve.alias property in your config without any additional plugins. Yes, you will have to use Webpack for your Nodejs projects.

How does the webpack.config.js look? Here are the necessary changes you need to add to the config file.

// .......
resolve: {
alias: {
'@config': path.resolve(__dirname, 'src/config'),
'@utils': path.resolve(__dirname, 'src/utils'),
'@locations': path.resolve(__dirname, 'src/utils/location-services/location-reciever'
'@stores': path.resolve(__dirname, 'src/stores')
},
extensions: ['.js', '.jsx', '.css', '.less']
}
// .......

After the webpack configuration, the import can be simplified in the following way making is cleaner and less complicated.

import { getStorage, setStorage } from '@config/storage'
import { helpers } from '@utils'
import getLocation from '@locations'
const location = getLocation()

Seems fair to configure webpack in a Nodejs project, but what about projects bootstrapped with CRA. Do you React people actually want to run npm eject just to manage aliases? That can be even greater pain than those longer relative imports.

CRACO saves the day

CRACO short for Create React App Config Override is an npm package that replaces the default react-scripts in a CRA project and overrides some of the webpack configurations. CRACO with craco-alias plugin can help us achieve the same.
Here is how the configuration file will look like.

const CracoAlias = require('craco-alias')
const alias = {
'@modules': 'modules',
'@utils': 'utils',
'@request': 'request',
'@styled': 'styled',
'@pages': 'pages',
}
module.exports = {
plugins:[
{
plugin: CracoAlias,
options: {
source: 'options',
baseUrl: './src',
aliases: alias
}
}
]
}
view raw craco.config.js hosted with ❤ by GitHub

Are we done?

Apparently, all of these configurations absolutely breaks the IntelliSense for these imports in Visual Studio Code.

Luckily, IDEs like Visual Studio Code have the option to let them know how to resolve these aliases just by adding a jsconfig.json file with appropriate options. Just like the one below.

{
"compilerOptions": {
"target": "es2017",
"allowSyntheticDefaultImports": false,
"baseUrl": "./src/",
"paths": {
"@modules/*": ["modules/*"],
"@utils/*": ["utils/*"],
"@request/*": ["request/*"],
"@styled/*": ["styled/*"],
"@pages/*": ["pages/*"]
}
},
"exclude": ["node_modules", "dist"]
}
view raw jsconfig.json hosted with ❤ by GitHub

Yeah yeah, that's all, I know it's a lot of boilerplate but in an enterprise-level project where codebase grows every day, it's a must-have. And that sums up everything you need to know for creating aliases for Javascript imports.

Enjoyed reading the piece? A few Claps and Shares are all I need. Cheers.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay