最近使用 create-react-app test --scripts-version=react-scripts-ts@4.0.8
方式创建了react项目,并且使用了typescript,但是在使用Code Splitting
时,官方文档提到了使用最新的特性:
React.lazy
The React.lazy
function lets you render a dynamic import as a regular component.
Before:
import OtherComponent from './OtherComponent';
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
After:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
但是,在项目中会发现react里并没有发现导出lazy、Suspense
找了各种文档,最终发现了问题:
React.lazy type definition not found for lazy, Suspense
Add more of the new features added in React 16.6
在vscode里面import的react使用的是@types/react库,这个库版本还是16.4,没有把react16.6里面的新特性merge进去,所以才导致项目报错。
临时解决方法:
const lazy = (React as any).lazy
const Suspense = (React as any).Suspense
永久解决方法:
等待@types/react升级到16.6以上.
网友评论