首页 > 解决方案 > @types/core-js 用于动态导入“core-js/stable”

问题描述

这就是我所做的,index.js以避免向我的所有用户提供 polyfill。

index.js

const renderApp = () => {
  ReactDOM.render(
    <App
      firebase={firebase}
    />
    ,document.getElementById("root") as HTMLElement
  );
};

/* ############################ */
/* #### CHECK FOR POLYFILL #### */
/* ############################ */

if (
  'fetch' in window &&
  'Intl' in window &&
  'URL' in window &&
  'Map' in window &&
  'forEach' in NodeList.prototype &&
  'startsWith' in String.prototype &&
  'endsWith' in String.prototype &&
  'includes' in String.prototype &&
  'includes' in Array.prototype &&
  'assign' in Object &&
  'entries' in Object &&
  'keys' in Object
) {
  renderApp();
} else {
  import(
    /* webpackChunkName: "core-js-stable" */
    /* webpackMode: "lazy" */
    'core-js/stable'                          // <---- DYNAMIC IMPORTED "core-js/stable"
  ).then(renderApp);
}

但是我在core-js/stable包的动态导入中收到“隐式任何类型”警告。而且由于我通常使用--noImplicitAny标志,我的项目不会像那样编译。

在此处输入图像描述

奇怪的是我已经安装了@types/core-js package

在此处输入图像描述

为什么 Typescript 找不到 core-js 包的类型?

注意:如果我使用常规导入它,import "core-js/stable"我不会收到此警告/错误。

此外,如果我只在core-js没有/stable路径的情况下动态导入它,我不会收到任何警告/错误。

就像,这很好:

 import(
    /* webpackChunkName: "core-js-stable" */
    /* webpackMode: "lazy" */
    'core-js'
  ).then(renderApp);

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "esModuleInterop": true,
    "jsx": "react",
    "module": "CommonJS",
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "ES5",
    "paths": {
      "@src/*": ["./src/*"],
    }
  },
  "include": [
    "src/**/*"
  ]
}

标签: javascripttypescripttypescore-js

解决方案


这是我为摆脱错误/警告所做的。

从 Typescript 文档中得到了这个想法:

https://www.typescriptlang.org/docs/handbook/namespaces.html#working-with-other-javascript-libraries

我已经为环境声明和一个index.d.ts文件创建了这个文件夹

/types/ambient/index.d.ts

索引.d.ts

declare module 'core-js/stable';

并且index.tsx您必须使用三斜杠指令引用d.ts您创建的文件。

索引.tsx

/// <reference path="./types/ambient/index.d.ts"/>

(...) OTHER CODE

import(
  /* webpackChunkName: "core-js-stable" */
  /* webpackMode: "lazy" */
    'core-js/stable'
).then(renderApp);

现在一切正常,没有错误/警告。

在此处输入图像描述


推荐阅读