By default, one can import a component defined in ./MyComponent/index.ts
by import MyComponent from "MyComponent"
.
To avoid having 12 tabs named "index" in my IDE, I name the component file MyComponent.ts
too. But now if I import the component, I have import MyComponent from "MyComponent/Mycomponent"
.
Since the file name always matches the directory name, I was wondering if I can add a dynamic resolver to my project configuration, e.g. tsconfig.json
, which maps "MyComponent"
to "MyComponent/MyComponent"
.
CodePudding user response:
Yes, you can use a custom path mapping in your project's TypeScript configuration file (tsconfig.json) to map the import path for your component to just "MyComponent" instead of "MyComponent/MyComponent".
To do this, you will need to add a paths property to your tsconfig.json file with an entry that maps "MyComponent" to the full path of your component file. Here is an example of how this might look:
{
"compilerOptions": {
// Other compiler options
},
"paths": {
"MyComponent": ["src/components/MyComponent/MyComponent"]
}
}
In this example, the paths property maps the import path "MyComponent" to the path src/components/MyComponent/MyComponent, which is the location of the component file on your file system.
Once you have added the paths property to your tsconfig.json file, you can import your component using the shorter import path:
import MyComponent from "MyComponent";
This will use the mapping you defined in the tsconfig.json file to resolve the import path to the correct location on your file system.
CodePudding user response:
You can write a index.ts
file inside ./MyComponent
with the following:
export * from "./MyComponent";
And then you can import MyComponent
with the following:
import MyComponent from "./MyComponent";`