我正在尝试重构 React 18 应用程序以使用延迟加载 described in the docs :
The best way to introduce code-splitting into your app is through the dynamic import() syntax.
我的原始代码(工作):
import addMobileAppStartupListeners from './components/listeners/addMobileAppStartupListeners';
const startApp = () => {
if (isPlatformMobile()) {
addMobileAppStartupListeners();
}
startAccessibilityTestingIfDebug();
};
addMobileAppStartupListeners.tsx
const addMobileAppStartupListeners = () => {
document.addEventListener(
'deviceready',
() => {
// Method called when tapping on a notification
PluginPushNotifactions.addListener(
'pushNotificationActionPerformed',
(notification: PluginActionPerformed) => {
debugLog('push registration tapped', notification);
},
);
},
false,
);
};
export default addMobileAppStartupListeners;
由于这是默认导出,我认为我可以使用导入:
const startApp = () => {
if (isPlatformMobile()) {
import('./components/listeners/addMobileAppStartupListeners').then(
(addMobileAppStartupListeners) => {
addMobileAppStartupListeners();
},
);
}
startAccessibilityTestingIfDebug();
};
但是 TypeScript 提示:
[react-scripts] ERROR in src/index.tsx:41:9
[react-scripts] TS2349: This expression is not callable.
[react-scripts] Type 'typeof import("/Users/private/d/ionic/src/components/listeners/addMobileAppStartupListeners")' has no call signatures.
我不知道如何解决这个问题。我对 TypeScript 的了解还很初级。我想我需要给它导入返回的函数的类型,但我不知道该怎么做。
** 环境详细信息***
typescript 4.9.5
{
"compilerOptions": {
"target": "es2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true
},
// Config files.
"files": [
"capacitor.config.ts",
"ionic.config.json",
"lingui.config.ts",
],
"include": [
"src",
"tests/playwright",
],
}
最佳答案
从文档示例中可能不明显的是,动态导入的结果是 module本身:
Returns a promise which fulfills to a module namespace object: an object containing all exports from
moduleName
.
因此,如果您的模块有默认导出,请确保使用 .default
属性来获取实际导出的函数:
import('./components/listeners/addMobileAppStartupListeners').then(
// Result is the module containing all its exports, including default
(addMobileAppStartupListeners) => {
// Here you want the default exported function
addMobileAppStartupListeners.default();
}
);
关于reactjs - 在 React 中导入延迟加载时的 TS2349,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75579459/