DEV Community

Path aliases with TypeScript in Node.js

Lars Wächter on February 06, 2019

This post was originally published on my blog. Some days ago I included path aliases in my TypeScript Node.js projects. Since they make the cod...
Collapse
 
davestewart profile image
Dave Stewart •

I've just released a new package Alias HQ, which allows you to reuse your js/tsconfig.json path aliases in Webpack, Jest, Rollup, or any other library.

Just call hq.get('<library name>') in the config file you want to use aliases in, and you're done:

github.com/davestewart/alias-hq

Collapse
 
js2me profile image
Sergey S. Volkov •

Thanks!

Also I find out that if we have webpack in project we just use resolve.alias option:


  resolve: {
    extensions: ['.js', '.ts', '.tsx', '.styl'],
    mainFields: ['module', 'browser', 'main'],
    alias: Object.keys(tsconfig.compilerOptions.paths).reduce((aliases, aliasName) => {

      aliases[aliasName] = path.resolve(__dirname, `src/${tsconfig.compilerOptions.paths[aliasName][0]}`)

      return aliases
    }, {})
  },
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jimstack profile image
jimstack •

Thank you! I read several posts about using path aliases and thought it was perfect for my project, but I hit the *cannot find module" issue. I was banging my head off the desk all afternoon. It's been really difficult to find anything on this.

Collapse
 
darrensapalo profile image
Darren • • Edited

Had an issue with zeit/pkg because the generated files (in the dist folder) still had the @/dir/to/your/file references, which pkg could not handle.

In case you need to change your js files from the @/your-file back into their ../../../your-file form, you can use ef-tspm to bring it back. Note, if you do so, you won't need to deal with the extra steps for the module-alias specified above. Trade-off is you have an additional build step. So first you would tsc to build the typescript code, then ef-tspm to properly remove the module aliases.

Collapse
 
loclv profile image
Luu Vinh Loc •

Thanks for sharing!

Collapse
 
forsetius profile image
Marcin Paździora •

Thanks for the article!

However, to utilize this solution we have to define the aliases in 2 locations: tsconfig.json and package.json. Is it possible to avoid this duplication?

Collapse
 
etroynov profile image
Evgeniy Troynov •

You can use:
npmjs.com/package/tsconfig-paths

it much easier

Collapse
 
itsikbelsonspotlight profile image
itsikbelson-spotlight • • Edited

I also kept receiving module_not_found while running ts-node.
The way that worked for me (taken from stackoverflow.com/questions/566507...

In tsconfig.json add the following section:

"ts-node": {
      "require": ["tsconfig-paths/register"]
},
Enter fullscreen mode Exit fullscreen mode

In order to make the script run on the compiled js (for production distribution), you can defined the following script in package.json:

"scripts": {
      "start": "TS_NODE_BASEURL=./dist node -r tsconfig-paths/register dist/index.js"
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to run npm i tsconfig-paths

Collapse
 
empflow profile image
empflow •

Thank you so much! I've probably spent like 6 hours in total trying to get this to work and I finally see the listening on port 3000 log 😁

Collapse
 
vitalodev profile image
Vital •

you made my day, thx!

Collapse
 
henrrymaximo profile image
Henrique Maximo Lima •

for who wants using @/* at importings, only insert:

"""
"baseUrl": "./",
"paths": {
"@/": ["./src/"]
}

"""
Example: import { authenticateFromGithubCode } from "@/use-cases/authenticate-from-github-code";

Collapse
 
solitrix02 profile image
Sanchit Bajaj •

I have setup of this with tsconfig-paths but I am getting module not found error when I am running my dist file. Do you have any idea?

Collapse
 
ksnyde profile image
Ken Snyder • • Edited

These aliases -- which I've grown used to on the frontend frameworks which use webpack -- are a VERY welcome addition to writing typescript on the backend (or in other library code). My one question comes down to testing. I have a library with hundreds of tests but right now none of them run because I'm using Mocha/Chai with ts-node and I'm not sure but I think that ts-node is not able to use the alias.

The command I use is:

./node_modules/.bin/mocha --no-timeouts --require ts-node/register --exit

This is a pretty standard way of testing as it allows you to test directly on the source rather than needing to transpile before testing.

Collapse
 
devoresyah profile image
DeVoresyah ArEst •

hi, thanks for your sharing. I've followed step-by-step from the article, but however I can't click to navigate to the path when using alias in my vscode. Normally when I click the path, it goes directly to the path... can you help me with this case? I'm not using typescript, so I can't add tsconfig

Collapse
 
stanyeshchenko profile image
Stanislav Yeshchenko • • Edited

Did you have a situation where shared folder has its own package.json with node_modules?

During compilation node_modules are not included in the dist folder, and the compiler is complaining about missing npm modules from the shared

Collapse
 
shubhamsinha profile image
Shubham Sinha •

Does VSC automatic imports work with this?

Collapse
 
larswaechter profile image
Lars Wächter •

Yes, it does.

Collapse
 
theaccordance profile image
Joe Mainwaring •

How complex is the folder organization for your source code? I had looked into this but it doesn't have as much value with flatter source-orgs

Collapse
 
larswaechter profile image
Lars Wächter •

The complexity of my folder organization depends on the project. Mostly I have some root folders like: config, rest, services that I declare path aliases for. Inside these I have my components for example.

Collapse
 
ruslangonzalez profile image
Ruslan Gonzalez •

How cool is that eh! thanks for posting.

Collapse
 
coderarchive profile image
Lu-Vuong Le 🚀 •

For anyone reading this, when updating the tsconfig file, you'll need to add the "baseUrl" and "paths" options inside the "compilerOptions" object :)

Collapse
 
allcracked profile image
José Avilez •

Thanks a lot for sharing, I was getting crazy with the issues where modules were not being found.

Collapse
 
senpl profile image
Michał Urbanek •

I found that using extension to import marketplace.visualstudio.com/items... works good enough and not require much logic.

Collapse
 
miguelmota profile image
Miguel •

Thank you!

Collapse
 
dainiuss profile image
Dainius Stepulevicius •

Hey,

I have followed your tutorial by the letter and even restarted code editor but keep getting the error, no matter what I do

Collapse
 
larswaechter profile image
Lars Wächter •

Which error?

Collapse
 
dainiuss profile image
Dainius Stepulevicius •

the original error that article is about
'module is not found'

Collapse
 
ayushnawani profile image
Ayush Nawani •

Thanks for sharing.

Collapse
 
liyaxuanliyaxuan profile image
liyaxuanliyaxuan •

marked, thanks!

Collapse
 
pak11273 profile image
Isaac Pak •

I don't get any errors and I don't have to install any npm packages...

Collapse
 
ramtob profile image
Ram Tobolski •

Hello.
I don't understand how this solution is supposed to work in production.
We don't have a package.json file in production. So how the aliases will be recognized?

Collapse
 
larswaechter profile image
Lars Wächter •

The path aliases only play a role during development since the TS code is compiled to JS.

Collapse
 
deschant profile image
Deschant Kounou •

I couldn't get the aliases working without first building the project since they are registered using the dist folder. Feels hacky. Is there a way around this ?

Collapse
 
dev_toykam profile image
toykam •

Thank you for sharing this, it was soo helpful.