Szopinski
Szopinski

Reputation: 810

ts-loader: import .ts module from other Yarn workspace

I have Yarn workspace structured like this:

/project
  package.json
  /packages
    /app
      package.json
      webpack.config.js
      tsconfig.json
      /src
        index.ts
    /api-adapter
      package.json
      /src
        api.ts

To build /app package I'm using Webpack with ts-loader. Here is configuration:

// /packages/app/webpack.config.js
module.exports = {
    entry: path.resolve(__dirname, "src/client/index.ts"),
    mode: "development",
    devtool: "inline-source-map",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: "ts-loader",
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"]
    },
    output: {...}
};

and tsconfig.json

{
  "compilerOptions": {
    "module": "es6",
    "target": "es6",
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "noImplicitAny": true,
    "outDir": "./dist/",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "lib": ["dom", "es6", "webworker"]
  }
}

When I want to import module from other workspace:

// /packages/app/src/index.ts
import { fetchSomething } from "api-adapter/src/api";

an error occurred:

ERROR in ../api-adapter/src/api.ts
Module build failed (from /home/user/project/node_modules/ts-loader/index.js):
Error: Typescript emitted no output for /home/user/project/packages/api-adapter/src/api.ts.

but when I add extension to import, everything works fine:

// /packages/app/src/index.ts
import { fetchSomething } from "api-adapter/src/api.ts";

How can I fix webpack config to import any workspace module as Typescript without extension?

I've tried already:

rules: [{
  test: /\.tsx?$/,
  use: "ts-loader",
  exclude: /node_modules/,
  include: [
    __dirname,
    path.resolve(__dirname, "../packages")
  ],
}]

with:

ERROR in ../api-adapter/src/api.ts 3:34
Module parse failed: Unexpected token (3:34)
You may need an appropriate loader to handle this file type.

Upvotes: 4

Views: 3222

Answers (1)

Szopinski
Szopinski

Reputation: 810

Webpack config was correct. ts-loaderfound a file, but the compiler rejected it: Error: Typescript emitted no output because of path:

// tsconfig.json
{
    "compilerOptions": {
      ...
    },
    "include": [
        "src/**/*",
        "../../packages/**/*"
    ]
}

Upvotes: 3

Related Questions