Get path relative to project directory from within Typescript module compiled to JS

Viewed 21

I have a directory structure like

- project
|- build
|- src
 |- index.ts
 |- file.txt

The typescript is compiled to the build directory and executed from there. I'm looking for a reliable way to access file.txt from the compiled module without having to account for the location of the build output.

For example, I could just assume that the file is at ../src/file.txt relative to the index.js in build but if the build output changes, that needs to be changed as well.

Is there possibly a way to pass root directory into an environment variable before the typescript is compiled?

1 Answers

If you using webpack, you can insert a resolve, see documentation: https://webpack.js.org/configuration/resolve/

and a example:

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
    },
  },
};

You can too use vscode jsconfig.json you can use compilerOptions, see documentation: https://code.visualstudio.com/docs/languages/jsconfig

example:

{
  ...
  "compilerOptions": {
    "target": "es2015",
    "module": "esnext",
    "baseUrl": ".",
    "paths": {
      "@assets/*": ["src/assets/*"],
      "@background/*": ["src/background/*"],
      "@frontend/*": ["src/frontend/*"],
      "@mixins/*": ["src/frontend/mixins/*"]
    }
  }
}
Related