How to handle paths for transpiled JS?

16 Views Asked by At

So I have a monorepo workspace with a common folder that's shared with my express app. My common folder transpiles to JS inside common/dist, and i would like my transpiled express code to be able to access that. So how do I handle imports when my ts files use common/schema but the js files will need common/dist/schema?

1

There are 1 best solutions below

0
Troy Calderon On

To handle imports when your TypeScript files use common/schema but the JavaScript files will need common/dist/schema, you can use TypeScript path mapping and configure your module resolution appropriately.

Here's how you can set it up:

  1. Configure TypeScript Path Mapping: In your TypeScript configuration file (tsconfig.json), you can define path mappings to alias common/schema to common/dist/schema. This allows TypeScript to resolve imports from common/schema to the correct transpiled JavaScript files.

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "common/schema": ["common/dist/schema"]
        }
      }
    }
    
  2. Use Relative Imports in TypeScript Files: Inside your TypeScript files, import modules using relative paths (import ... from './schema'). TypeScript will resolve these imports based on the path mapping configuration.

  3. Compile TypeScript Code: When you compile your TypeScript code, ensure that it generates JavaScript files in the correct directory (common/dist).

  4. Require Transpiled Modules in JavaScript Files: In your JavaScript files, you can require transpiled modules using the appropriate relative path (require('./schema')).

With this setup, TypeScript will resolve imports from common/schema to the correct transpiled JavaScript files located in common/dist/schema, allowing your TypeScript and JavaScript files to work seamlessly together within your Express application.