Reputation: 2267
In my React project I have a module alias defined in webpack config. I want to start moving over to Typescript.
// I tried to simplify the setup as much as it makes sense
This is my tsconfig.json
in the root folder:
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"moduleResolution": "node",
"jsx": "react",
"noImplicitAny": true,
"strictNullChecks": true,
"sourceMap": true,
"lib": [
"dom",
"es2015",
"es2016"
],
"baseUrl": "./src",
"paths": {
"app": ["./app"]
}
},
"include": [
"src/**/*"
]
}
This is my project structure:
[rootDir]
|
|- [src]
| |
| |-[app]
| |
| |-[components]
| | ... react components live here
| |- Test.tsx
| |- SomeComponent.tsx
| |- index.js (export { default as Test } from './Test')
|
|- tsconfig.json
|- webpack.config.js
I use the awesome-typescript-loader
with Webpack 2 and I also included the plugin there to load the paths. I also use Visual Studio Code and it has Typescript built in, but that shows the same error.
In my Typescript component SomeComponent.tsx
I want to include another component like so:
import * as React from 'react'
import { Test } from 'app/components'
I get the following error:
Cannot find module 'app/components'
Upvotes: 50
Views: 55100
Reputation: 1833
I recommend using tsc-alias. See the full example in this thread.
Upvotes: 1
Reputation: 2612
For a folder structure like:
[rootDir]
|
|- [src]
| |
| |-[app]
| |
| |-[components]
| | ... react components live here
| |- Test.tsx
To import like this:
import { Test } from 'app/components'
You need to add "src/components"
beside "src/components/*
in tsconfig.json
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"app*": ["src/components", "src/components/*"]
}
}
Upvotes: 3
Reputation: 2267
The solution is to edit the paths config to find nested files.
"baseUrl": ".",
"paths": {
"app*": ["src/app*"]
}
Now when I add import { Test } from 'app/components'
Typescript will look into src/app/components/index.js
and it works. I also like to add @
to aliases to avoid conflicts with other modules. Like so:
"@app*": ["src/app*"]
Upvotes: 51