David Alsh
David Alsh

Reputation: 7609

tsconfig "paths" are compiled and included by tsc? How can you stop this?

Imagine the following project structure

/src
  index.ts
  a.ts
/external
  external.ts

When using the following tsconfig.json:

{
  "compilerOptions": {
    "outDir": "dist",
    "declarationDir": "dist",
    "declaration": true,
    "baseUrl": "./src",
    "paths": {
      "@external/*": "../external/*"
    }
  },
  "exclude": [
    "dist"
  ]
}

The output will contain the external package

/dist
  /src
    a.d.ts
    a.js
    index.d.ts
    index.js
  /external
    external.d.ts
    external.js

When what I wanted was

/dist
  a.d.ts
  a.js
  index.d.ts
  index.js

Even when I add "external" in the exclude option, it still compiles and includes the external package.

Is there a way to avoid compiling the external module and consume it as it is?

EDIT: For context, the external module is compiled separately. The path is simply for getting types at dev time.

Upvotes: 3

Views: 2063

Answers (2)

Fahd Lihidheb
Fahd Lihidheb

Reputation: 710

you can use webpack configs like so

const webpack = require('webpack');

module.exports = {
  externals: {
    '@external': 'external'
  }
};

and build your applications with --extraWebpackConfig webpack.extra.js.

Upvotes: 0

ford04
ford04

Reputation: 74500

TS compiles all files in the project directory per default. You can exclude input files, but if you import something from ../external/* via module resolution, there is no way to exclude the module.

What is happening is: TS sees, that one compilation source is outside ./src (external.ts) and sets its rootDir config option automatically to be the parent folder of ./src and ./external. That is the reason, why you get the additional nesting in ./dist.

So what to do? You can rename the external.ts file to a .d.ts extension, so a) you still have the types, b) the compiler will see the file only as input and doesn't create nested output in ./dist anymore. (But I am not sure, how your separate build works.)

In addition, it could probably be a good idea to set the external module as separate npm package, which you then will have placed in node_modules via npm link or other mechanisms. The compiler doesn't compile them per default, so it also solves your issue.

Upvotes: 1

Related Questions