Tìm kiếm trang web

reactjs - TypeScript Cảnh báo: Xuất, xuất lại dưới tên, không tìm thấy (các xuất có thể)


Với cấu trúc thư mục này

├──components/
|  └─Employee/
|    └─employee.tsx
|    └─index.ts
|  └─app.tsx

Tôi đang xuất một loại và một thành phần

nhân viên.tsx

import React, { FC } from 'react'

export type EmployeeState = {
  Name: string
  EmployeeId: number
}

type EmployeeProps = {
  employees: EmployeeState[]
}

export const Employee: FC<EmployeeProps> = ({ employees }) => {
  return (
    <ul>
    {
      employees.map((employee) => (
        <li key={employee.EmployeeId}>
          <h2>{employee.Name}</h2>
        </li>
      ))
    }
    </ul>
  )
} 

Và sau đó xuất từ index.ts trong thư mục Employee

index.ts

export { EmployeeState, Employee } from './employee'

Khi tôi cố gắng nhập từ app.tsx

app.tsx

...
import { EmployeeState, Employee } from '@components/Employee'
...

Tôi nhận được cảnh báo này từ TypeScript:

WARNING in ../src/components/Employee/index.ts 4:0-53
`export 'EmployeeState' (reexported as 'EmployeeState') was not found in './employee' (possible exports: Employee)`

Tôi đã có thể sửa cảnh báo bằng cách thực hiện thay đổi này:

Nhân viên/index.ts

Cũ:

export { EmployeeState, Employee } from './employee'

Mới:

export * from './employee'

Nhưng tôi vẫn không hiểu tại sao nó lại không hoạt động theo cách ngược lại.

Câu trả lời #1

Tôi cũng gặp vấn đề này và sau khi tìm hiểu thêm đã tìm thấy Vấn đề GitHub này, nó đi vào chi tiết nếu bạn quan tâm: https://github.com/webpack/webpack/issues/7378#issuecomment-683894656

Dù bằng cách nào, giải pháp là type của bạn cần được xuất theo cách khác. Cập nhật mã của bạn như sau nên sẽ khắc phục được vấn đề của bạn.

export { Employee } from './employee'
export type { EmployeeState } from './employee'

Bạn cũng có thể làm những điều sau, cảm ơn @bmacher vì nhận xét!

export { Employee, type EmployeeState } from './employee'

Nếu bạn quan tâm đến việc tìm hiểu thêm về cách thức và lý do đằng sau điều này, đây là một bài viết hay: https://javascript.plainenglish.io/leveraging-type-only-imports-and-exports-with-typescript-3-8-5c1be8bd17fb

Bài viết liên quan