简体   繁体   中英

What is the correct way to import a file in typescript?

historically when importing javascript files, you name the file index.js and then import like so

import something from 'components/path/something' where the last something is a directory with the index.js file in

but with TS I get an error saying: no file or directory when I switch the file name to index.ts

2 solutions so far import something from 'components/path/something/index.ts'

or

import something from 'components/path/something/something'

not a huge fan of either, is there a better approach to this?

There is no correct way:

Imports are usually relative:

import whatever from '../another/folder/'; // will import index

Of course you can adapt this behavior in tsconfig.json:

{
  ....
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@services/*": ["services/*"],
      "@shared/*": ["shared/*"],
      "@models/*": ["models/*"],
    },
    ...
  }
}

Provides you an "absolute project path":

import WhateverService from '@services/WhateverService';

https://www.typescriptlang.org/docs/handbook/modules.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM