javascript - @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/**/*"
]
}
解决方案
这是我为摆脱错误/警告所做的。
从 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);
现在一切正常,没有错误/警告。
推荐阅读
- three.js - 如何在 ThreeJS 编辑器中对添加的形状使用灯光效果
- mysql - 创建删除 14 天前数据的触发器
- api - GitHub API Access 拒绝尝试通过 API 更新工作流
- c# - 在 box colliders 和 tilemaps 之间遇到一个奇怪的碰撞错误
- visual-studio-code - NLog 没有向控制台输出任何内容
- macos - macOS Big Sur 上的 Netbeans Apache 12.2 只能以超级用户身份正常运行
- javascript - 如何在反应类之间共享数据?
- r - 根据与字典中任何术语的匹配创建二进制是/否动物变量,R中的“动物”
- objective-c - openUrl 命令适用于 Obj-C 但不适用于 Swift
- c++ - std::uninitialized_default_construct() 和 std::uninitialized_value_construct() 有什么区别?