My TypeScript Software Design & Architecture book just prelaunched! Check out solidbook.io.
Close

How to Import Modules using Absolute File Paths with TypeScript

Sep 12th, 2019 / 1 min read / Share / Edit on GitHub
In this quick blog post, I'll show you how you can configure TypeScript to use absolute file paths.

It used to suck having to type ../../../../ (and so on) to import a module when coding in TypeScript.

You can fix that by setting a baseUrl property in your tsconfig.json.

tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "pretty": true,
    "sourceMap": true,
    "target": "es6",
    "outDir": "./dist",
    "baseUrl": "./src", /* This is where all your code is*/
    "typeRoots" : ["./node_modules/@types", "./src/@types"]
  },
  "include": [
    "src/**/*.ts",
  ],
  "exclude": [
    "node_modules"
  ]
}

Boom, you're all set.

Now go try to import a module. The compiler should be able to help you out now.

src/modules/blog/useCases/getAllAuthors/GetAllAuthors.ts

Absolute imports

See the absolute import?

Say goodbye to those relative path staircases ../../../../ 👋.



Discussion

Liked this? Sing it loud and proud 👨‍🎤.


0 Comments

Be the first to leave a comment

Submit

Stay in touch!



About the author

Khalil Stemmler

Khalil Stemmler is a Developer / Designer and co-founder of Univjobs. He frequently publishes articles about Domain-Driven Design and Advanced TypeScript & Node.js best practices for large-scale applications.



View more in TypeScript



You may also enjoy...

A few more related articles

Functional Error Handling with Express.js and DDD | Enterprise Node.js + TypeScript
Aug 14th, 2019 / 16 min read
How to expressively represent (database, validation and unexpected) errors as domain concepts using functional programming concept...
An Introduction to Domain-Driven Design - DDD w/ TypeScript
Jul 30th, 2019 / 12 min read
Domain-Driven Design is the approach to software development which enables us to translate complex problem domains into rich, expr...
Handling Collections in Aggregates (0-to-Many, Many-to-Many) - Domain-Driven Design w/ TypeScript
Jul 25th, 2019 / 10 min read
In this article, we discuss how we can use a few CQS principles to handle unbounded 0-to-many or many-to-many collections in aggre...
Challenges in Aggregate Design #1 - Domain-Driven Design w/ TypeScript
Jul 25th, 2019 / 5 min read
In this series, we answer common questions in aggregate design. Here's an article orignating from the question, "How can a domain ...

Want to be notified when new content comes out?

Join 2000+ other developers learning about Domain-Driven Design and Enterprise Node.js.

I won't spam ya. 🖖 Unsubscribe anytime.

Get updates