reactjs TS2349在React中导入延迟加载时

smdncfj3  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(125)

我正在尝试重构一个React 18应用程序,以使用文档中描述的惰性加载:
将代码拆分引入应用的最佳方法是通过动态import()语法。
我的原始代码(工作):

import addMobileAppStartupListeners from './components/listeners/addMobileAppStartupListeners';

const startApp = () => {
  if (isPlatformMobile()) {
   addMobileAppStartupListeners();
  }
  startAccessibilityTestingIfDebug();
};

添加移动应用程序启动侦听器.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;

由于这是默认导出,我想我可以使用import:

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",
  ],
}
eyh26e7m

eyh26e7m1#

在docs示例中可能不太明显的是,动态导入的结果是 module 本身:
返回满足模块命名空间对象的承诺:包含从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();
  }
);

相关问题