为什么此Typescript导出未定义?

时间:2019-10-28 17:11:38

标签: javascript reactjs typescript

我正在尝试使用Typescript和React制作一个NPM软件包。 (TSX)

我正在关注this blog post,但尝试制造多个组件而不是一个。

当我尝试这样导入模块时

import { HelloWorld } from 'tsx_lib'

它显示为未定义

console.log(HelloWorld) //undefined

我的文件夹结构如下

src /
   GoodbyeWorld.tsx
   HelloWorld.tsx
   index.ts
index.d.ts

这是文件

GoodbyeWorld.tsx

import * as React from 'react';
import { GoodbyeWorldProps } from '../index';

export default class GoodbyeWorld extends React.Component<any, any> {
  render() {
    return <div style={{ color: this.props.color }}>Goodbye world!</div>;
  }
}

HelloWorld.tsx

import * as React from 'react';
import { HelloWorldProps } from '../index';

export default class HelloWorld extends React.Component<any, any> {
  render() {
    return <div style={{ color: this.props.color }}>Hello world!</div>;
  }
}

index.ts

export * from './HelloWorld';
export * from './GoodbyeWorld';

index.d.ts

import * as React from 'react';

export interface HelloWorldProps extends React.Props<HelloWorld> {
  color: string;
}

export interface GoodbyeWorldProps extends React.Props<HelloWorld> {
  color: string;
}

declare module 'hello-world' {

}

declare module 'goodbye-world' {

}

export class HelloWorld extends React.Component<HelloWorldProps, any> {}
export class GoodbyeWorld extends React.Component<HelloWorldProps, any> {}

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

export default class HelloWorld中的

HelloWorld.tsx是默认导出。

export * from './HelloWorld'将不会通过默认导出。

您有两个选择:

  1. HelloWorld.tsx命名的导出
export class HelloWorld extends Component { 
...
  1. 将默认导出映射到命名导出
export { default as HelloWorld } from './HelloWorld'