Skip to content

Instantly share code, notes, and snippets.

@jmcdo29
Created July 17, 2019 01:02
Show Gist options
  • Save jmcdo29/6276920d3dcbc1161c32a7a9a461f9c1 to your computer and use it in GitHub Desktop.
Save jmcdo29/6276920d3dcbc1161c32a7a9a461f9c1 to your computer and use it in GitHub Desktop.
tsconfig-paths bootstrap file to make registering paths work without problem

I've always had trouble using the given node -r tsconfig-paths/register path/to/main function from the command line, my paths never import correctly and I always seem to have an error when running after a build. After doing a bunch of digging around through packages and StackOverflow Q&A's I finally found a way to use tsconfig-paths programatically.

The tsconfig-bootstrap.js file makes use of tsconfig-pathsto register the paths from the compiler, and more than likely does exactly what tsconfig-paths/register is supposed to do. After requiring your tsconfig file you can access your baseUrl and paths via the JSON scheme of the config file to 100% programatically set your path imports to be correct, so that is anything changes in your config file this function doesn't need any chagning!

After you have the function set up, jsut add the following segment to your npm start command (whatever you have it called) and watch as your server fires up seamlessly:

# normal start without bootstrap
node path/to/main.js
# with tsconfig-bootstrap
node -r tsconfig-bootstrap.js path/to/main.js

Hope this helps out someone who's looking for an answer!

const config = require('./tsconfig.json'); // import your tsconfig.json where your paths are defined
const tsconfigPaths = require('tsconfig-paths');
tsconfigPaths.register({
baseUrl: config.compilerOptions.baseUrl,
paths: config.compilerOptions.paths
});
@ruslanguns
Copy link

Thanks for sharing it!

@johnbiundo
Copy link

Nice!

@digitalextremist
Copy link

MAD RESPECT from 772 days later, after this posted by @rubiin:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment