【问题标题】:Typescript export default function打字稿导出默认功能
【发布时间】:2016-02-10 14:17:01
【问题描述】:

我当前的 typescript 版本是 1.6.2,我们将其编译为 ECMA 5。我是 TypeScript 的新手,所以请理解。这些是导入的库类型。

redux-thunk.d.ts:

    declare module "redux-thunk" {
    import { Middleware, Dispatch } from 'redux';

    export interface Thunk extends Middleware { }

    export interface ThunkInterface {
        <T>(dispatch: Dispatch, getState?: () => T): any;
    }

    var thunk: Thunk;

    export default thunk;
}

在 app.ts 中:

import thunk from "redux-thunk";

console.log(thunk);

我越来越不确定。这是取自的代码: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/redux-thunk/redux-thunk-tests.ts(7行和16行)

我在 typescript 中使用默认导入的所有库都有同样的问题。

编辑: @Steve Fenton 我正在使用 npm 为我完成这项工作。我刚刚注意到问题出在 Typescript 编译器上。当我使用导出默认功能创建打字稿文件时,例如:

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

通知exports.default

当我查看从 npm 下载的 redux-thunk.js 文件时,有:

exports.__esModule = true;
exports['default'] = thunkMiddleware;

function thunkMiddleware(_ref) {
    var dispatch = _ref.dispatch;
    var getState = _ref.getState;

    return function (next) {
        return function (action) {
            return typeof action === 'function' ? action(dispatch, getState) : next(action);
        };
    };
}

module.exports = exports['default'];

通知module.exports = exports['default'];

如果我将 redux-thunk 类型输入 Babel 编译器,我会得到 exports['default'] 样式的结果。

最重要的部分是,当我将 redux-thunk.js 中的 export['default'] 样式替换为 exports.default 样式时,一切正常。这是我的编译器的问题吗?

【问题讨论】:

  • 使用 ES5 你可以使用import thunk = require('redux-thunk')。如果你想使用import import * as thunk from 'redux-thunk' 或 import {thunk} from 'redux-thunk'
  • @Rik import thunk from "redux-thunk" 有什么区别;并从“redux-thunk”导入*作为thunk; ?如果只有一个导出默认值不应该都返回相同的?
  • 说实话,我不知道为什么它不起作用。也许是 ES6 语法。我不是打字大师。
  • 你如何在你的应用程序中包含用于 redux-think 的实际 JavaScript 文件?
  • @SteveFenton 请查看编辑

标签: javascript typescript default


【解决方案1】:

我的朋友刚刚在github上得到了答案: https://github.com/Microsoft/TypeScript/issues/5565#issuecomment-155216760

ahejlsberg 答案:似乎“redux-logger”模块已被转译 与巴别塔。当 Babel 转译一个模块,它的唯一导出是 export default 它注入一个 module.exports = exports["default"];进入 生成的代码,导致导出的对象成为函数 本身(而不是具有作为 默认属性)。与 _interopRequireDefault 魔法配对时 Babel 为导入生成的净效果是一个假模块 创建了具有默认属性的对象,现在可以使用该函数 作为 _reduxLogger2.default 访问。

TypeScript 不会做任何这种魔法(有关详细信息,请参阅此处)。 为了让 TypeScript 使用该模块,您需要更改 redux-logger.d.ts 声明文件以实际反映正在发生的事情 开

【讨论】:

    猜你喜欢
    • 2017-02-06
    • 2016-01-23
    • 2019-12-11
    • 2021-02-07
    • 2018-04-17
    • 2017-09-23
    • 2020-05-17
    • 2021-12-19
    • 2013-03-17
    相关资源
    最近更新 更多