gpt4 book ai didi

typescript - 缺少值。导入模块的默认值

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:29 25 4
gpt4 key购买 nike

与 webpack、react 和 typescript 战斗。核心问题是 TS 编译代码在导出组件上引用“.default”时的值。

我可以修改 *.d.ts 文件,也可以更改代码,但我的尝试并没有太大的不同。使其成为 = require("...") 只会产生类型错误。

具有以下 react 文件:

import * as React from 'react';
import Paragraph from 'grommet/components/Paragraph';

export class Footer extends React.Component<Props, any> {
render() {
// Works -- return <span>Hello</span>;
return (
<Paragraph>
Hello
</Paragraph>
);
}
}

转换为:

Object.defineProperty(exports, "__esModule", { value: true });
const React = __webpack_require__(12);
const Paragraph_1 = __webpack_require__(153);
class Footer extends React.Component {
render() {
return (React.createElement(Paragraph_1.default, null, "Hello"));
}
}
exports.Footer = Footer;

我注意到 Paragraph_1 是从 Grommet 导出的函数,而 Paragraph_1.default 是未定义的。

段落有以下“exports”——

Object.defineProperty(exports, "__esModule", {
value: true
});

// Lots of real code here...

Paragraph.displayName = 'Paragraph';
exports.default = Paragraph;
module.exports = exports['default'];

Grommet types.d.ts 文件说:

declare module "grommet/components/Paragraph" {
export default Grommet.Paragraph;
}

我的 tsconfig.json 文件包含以下内容:

{
"compilerOptions" : {
"moduleResolution": "node",
"importHelpers" : true,

"target": "es5",
"noImplicitAny": false,
"removeComments": true,
"sourceMap": true,
"module": "commonjs",
"experimentalDecorators": true,
"outDir": "out",

"allowSyntheticDefaultImports" : true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": false,
"suppressImplicitAnyIndexErrors": true,
"sourceMap": true,
"preserveConstEnums": true,
"noImplicitAny" : true,
"noEmitOnError" : true,
"noEmitHelpers" : false,
"noFallthroughCasesInSwitch" : true,
"noImplicitReturns" : true,
"noImplicitThis" : true,
"experimentalDecorators" : true,
"strictNullChecks" : true,
"pretty" : true,
"forceConsistentCasingInFileNames" : true,

"jsx": "react",
"lib" : [
"dom",
"es6",
"es2016",
"es2017.object"
]
},
"exclude" : [
"out",
"dist",
"node_modules"
],
"files": [
"app/index.tsx",
"types/grommet.d.ts"
]
}

最佳答案

while Paragraph_1.default is undefined.

这意味着类型定义:

declare module "grommet/components/Paragraph" {
export default Grommet.Paragraph;
}

是错误的。这只是我不喜欢 default 的众多原因之一:https://basarat.gitbooks.io/typescript/docs/tips/defaultIsBad.html

修复

如果必须,请修复类型定义:

 declare module "grommet/components/Paragraph" {
export Paragraph: typeof Grommet.Paragraph;
}

关于typescript - 缺少值。导入模块的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44202209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com