ddibiase
ddibiase

Reputation: 1502

Import TypeScript modules from local module into React app

I'm trying to separate my projects and keep logic as separate components that I will end up publishing. For now, before I do so, I'd like to keep it organized as such:

  1. A library of TS scripts in a project called project-a
  2. A separate React app that I created with create-react-app (using Typescript as the template) called project-b

The React app's .tsx components will pull from project-a's .ts files.

I've gone ahead in project-b and ran yarn add ../project-a. This installs the library as a dependency. I then import the .ts files and my code editor is able to see all the types and definitions really nicely. Great!

When I run the application, Webpack complains:

./node_modules/project-a/src/calc.ts 2:7
Module parse failed: Unexpected token (2:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
> export enum Position {
|   Inner = 0,
|   Outer = 1

I don't understand why it's not parsing the file as a .ts. The whole React application is setup with TypeScript and I'm even import some .ts files locally. Do I need to tell Webpack to handle the files imported from this module as Typescript source (assuming Webpack wouldn't attempt parsing them if it didn't need to)?

The React template didn't setup a webpack (I'm assuming it's using a hidden default) but I am able to adjust the tsconfig.json file. I added my modules direct path into the include array. That didn't seem to do much either.

Basically: how can I get passed the above error and continue importing the TypeScript files from my dependency module in my main application?

Upvotes: 7

Views: 6765

Answers (1)

Johannes Klauß
Johannes Klauß

Reputation: 11020

You have to compile down project-a to javascript and emit the typings file, because imports from packages have to be Javascript.

The type infos you get from external packages is delivered via the .d.ts file alongside the package.

When you import other packages, you always import the Javascript file. Even locally, Webpack doesn't compile the typescript for you, a loader during bundling does. So once running inside the browser, it's all Javascript. But you are trying to import a Typescript file during runtime.

Upvotes: 6

Related Questions