Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Usage with node not compatible with "outDir" #75

Open
nicojs opened this issue Jan 30, 2019 · 4 comments
Open

Usage with node not compatible with "outDir" #75

nicojs opened this issue Jan 30, 2019 · 4 comments

Comments

@nicojs
Copy link

nicojs commented Jan 30, 2019

Hi, it seems that tsconfig-paths is not compatible with the "outDir" compiler option.

For example:

$ node -r tsconfig-paths/register dist/index.js
internal/modules/cjs/loader.js:613
    throw err;
    ^

Error: Cannot find module '@common'

Reproduction steps:

// common/index.ts
export const foo = 'bar';
// index.ts
import { foo } from '@common';
console.log(foo);
// tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "baseUrl": ".",
    "outDir": "dist",
    "paths": {
      "@common": ["./common"]
    }
  }
}

Find files here:

tsconfig-paths-outDir.zip

after you've created the project, use these commands:

$ tsc 
$ node -r tsconfig-paths/register dist/index.js

Proposal

I propose either to use the outDir by default (breaking for ts-node users) or create a separate register hook for node js scenario's.

@nicojs
Copy link
Author

nicojs commented Jan 30, 2019

As a workaround, I've created this alternative register file.

const tsConfig = require("./tsconfig.json");
const tsConfigPaths = require("tsconfig-paths");
const path = require("path");

tsConfigPaths.register({
  baseUrl: path.resolve(tsConfig.compilerOptions.baseUrl || '', tsConfig.compilerOptions.outDir || ''),
  paths: tsConfig.compilerOptions.paths
});

Thanks for the public api! Love those things!

@swiatek25
Copy link

swiatek25 commented Feb 1, 2019

@nicojs your snippet does not work for cases like this:

tsconfig.json:

    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "@logger": [ "src/lib/logger" ]
    },
    ...

@dolsem
Copy link

dolsem commented May 19, 2019

@swiatek25 try something like this:

const tsConfig = require('./tsconfig.json');
const tsConfigPaths = require('tsconfig-paths');

const { baseUrl, outDir, paths } = tsConfig.compilerOptions;

const outDirPaths = Object.entries(paths).reduce(
  (outDirPaths, [k, v]) => Object.assign(
    outDirPaths,
    { [k]: v.map(path => path.replace(/^src\//, `${outDir}/`)) }
  ),
  {}
);

tsConfigPaths.register({ baseUrl, paths: outDirPaths });

@ejhayes
Copy link

ejhayes commented Apr 3, 2020

See #114

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants