my directory structure is:
|
|__src
| |_components
| |
| |_A
| |_index.tsx
|
|
tsconfig.json
package.json
I want to import A
like this:
import { A } from 'src/components/A';
My tsconfig.json looks like this:
{
"compilerOptions": {
"baseUrl": "",
"declaration": true,
"downlevelIteration": true,
"esModuleInterop": true,
"jsx": "react",
"lib": ["es5", "es2015", "es2016", "dom"],
"module": "esnext",
"moduleResolution": "node",
"noImplicitAny": true,
"noUnusedLocals": true,
"noImplicitReturns": true,
"outDir": "dist",
"removeComments": false,
"skipLibCheck": true,
"strict": true,
"strictFunctionTypes": false,
"strictNullChecks": false,
"suppressImplicitAnyIndexErrors": true,
"target": "es5",
"typeRoots": ["./node_modules/@types"],
"types": ["node", "jest"],
"paths": {
"*": ["./node_modules/@types/*", "./types/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["./node_modules", "./dist", "src/**/*.test.ts", "src/**/*.test.tsx"]
}
But the import does not work and I get the error:
can't find module 'src/components/A';
Using TypeScript If you need to set up absolute imports in your Typescript application add/update your tsconfig. json file in the root directory of the project. Then you need to update the compiler option baseUrl in the file.
import * as file4 from './file4'; An absolute import path is a path that starts from a root, and you need to define a root first. In a typical JavaScript/TypeScript project, a common root is the src directory. For file1.
According to create-react-app Docs, We can use absolute imports in our react project by configuring a jsconfig. json / tsconfig. json (for typescript projects) file in the root of our project. If you're using TypeScript in your project, you will already have a tsconfig.
In tsconfig.json
define paths
like this:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"src/*": [
"./src/*"
],
}
}
}
(and you have to import it with name of file as well)
import { A } from 'src/components/A/index'
based on the comments no need to import with file name as long as it is called index (With relative paths we can skip the /index)
Imports with absolute paths work for me using this configuration in tsconfig.json
:
{
"compilerOptions": {
"baseUrl": "src"
}
}
This is the complete tsconfig.json
that works for me in CRA app:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"baseUrl": "src"
},
"include": [
"src"
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With