- Published on
How to setup path alias Javascript in VSCode?
Problem: a lot ../ using require or import in Javascript
const { DoSomething } = require('../../lib/do-something')
... happy with that
const { DoSomething } = require('@lib/do-something')
Fun fact: Typescript is navite support path alias and you just setup with file tsconfig.json and VSCode support also.
How about with JavaScript?
Using package module-alias
- Install package
npm install module-alias
- Setup path alias in file package.json
{
"name": "path_alias",
"version": "1.0.0",
"description": "Setup path alias with Javascript",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"module-alias": "^2.2.2"
},
"_moduleAliases": {
"@api": "./api",
"@lib": "./lib"
}
}
- Require package in top of the main file (index.js) before any code.
require('module-alias/register')
Hold on, but you can go to define in VSCode
Let try with file jsconfig.json and enjoy
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./*"],
"@api/*": ["./api/*"],
"@lib/*": ["./lib/*"]
}
}
}
Source code: https://github.com/chuongtrh/path_alias