【问题标题】:How to use external library in a Typescript 2.0 project?如何在 Typescript 2.0 项目中使用外部库?
【发布时间】:2017-02-16 18:26:21
【问题描述】:

我有一个使用 Common JS 模块和 System JS 加载器的 Typescript 2.0 项目。我使用 Visual Studio 代码作为 IDE。我在我的项目中使用外部库(文件保护程序 JS)时遇到问题。

我通过 npm 安装了 librarytype definition。两者都分别出现在我的 node_modules 和 node_module/@types 中。

如何在我的用于保存 blob(转换为 JSON 字符串的对象)的函数中引用(导入)我的 TypeScript 代码中的文件保护程序 saveAs 函数?

我尝试了几种导入的变体,但似乎没有一个对我有用。我得到“index.d.ts”不是模块错误或“找不到模块”错误。

这是我尝试过的:

import filesaver = require('FileSaver'); //error: index.d.ts is not a module import {FileSaver} from 'file-saver'; //error: cannot find module file-saver

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "es2015", "dom"],
    "sourceMap": true,
    "pretty": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitUseStrict": false,
    "noFallthroughCasesInSwitch": true,
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules"
    ],
    "types": [
      "node"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "src"
  ],
  "compileOnSave": false
}

【问题讨论】:

  • 您能否展示您的 tsconfig.json(如果您使用的是一个)文件,并提供您尝试导入它的示例吗?
  • @DaveV - 将请求的信息添加到问题中。
  • 我之前说得太早了,但我认为我可以正常工作(或者至少可以解决)。我无法让import 工作,但我正准备做var fileSaver = require("file-saver");,然后像fileSaver.saveAs(); 一样打电话给saveAs
  • @DaveV - 在上面尝试了你的建议。获取fileSaver.saveAs is not a function 运行时错误。
  • 那我就不知所措了。查看类型定义文件,它看起来不正确(它实际上没有调用saveAs 一个函数)所以我不确定定义是否正确。

标签: angular typescript typescript-typings filesaver.js


【解决方案1】:

我在使用 System JS 模块加载器的 Angular 2 项目中遇到了同样的问题。 对我来说

import {saveAs} from 'file-saver';

有效,但只有在我在系统 JS 配置中明确将文件保护程序的模块格式设置为 cjs 之后:

"packages":{
     "file-saver":{
          "main":"FileSaver.js", 
          "format": "cjs"
     }
}

据我了解 SystemJS 默认会将文件保护程序识别为 AMD 模块。可能file-saver中的AMD模块定义有问题,但我对此没有很深的理解。 (另见https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js#L182

【讨论】:

  • P.S.:在设置 cjs mdoule 格式之前,我也遇到了@ebhh2001 的评论中提到的fileSaver.saveAs is not a function 问题
【解决方案2】:

这可能不是完美的解决方案,但以下三行在 IE 11 和 Chrome 中对我有用。

var saveAs = require('file-saver');
var blob = new Blob([JSON.stringify(myDataObject)], { type: 'text/plain;charset=utf-8' });
saveAs(blob, "file.txt");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多