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

时间:2017-05-26 12:56:09

标签: typescript typescript2.0

与webpack战斗,反应和打字稿。核心问题是,当值在导出的组件上时,TS编译的代码引用了“.default”。

我可以修改* .d.ts文件或者我可以更改代码,但我的尝试没有太大的区别。使它= require("....")只会产生类型错误。

请准备以下反应文件:

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未定义。

对于“出口” -

,段落有以下内容
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"
    ]
}

2 个答案:

答案 0 :(得分:0)

  

虽然Paragraph_1.default未定义。

这意味着类型定义:

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

错误。这只是我不喜欢defaulthttps://basarat.gitbooks.io/typescript/docs/tips/defaultIsBad.html

的众多原因之一

修复

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

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

答案 1 :(得分:0)

原来我解决的是我使用commonjs模块而不是es6。在我的tsconfig.json导入问题中更改以下行。

  "module": "es6",