【问题标题】:How to Polyfill Promise in Visual Studio 2017 Office Add-in TypeScript Project如何在 Visual Studio 2017 Office 插件 TypeScript 项目中填充 Promise
【发布时间】:2018-01-12 16:07:53
【问题描述】:

我在 Office 插件中使用 TypeScript,我想专门使用 async / await 函数。项目编译失败,出现“TS2468 TypeScript 找不到全局值‘Promise’”。

我在这里读到我必须为 Promise 创建一个 polyfill,但到目前为止还没有弄清楚如何让一个 polyfill 在 Visual Studio 2017 中工作。我正在尝试使用 core-js,并且有使用 npm install core-js 将其安装到项目中。我可以看到 core-js 安装在 node_modules 下。 npm 还创建了一个带有以下内容的 package.json 文件:

{ "requires": true, "lockfileVersion": 1, "dependencies": { "core-js": "^2.5.3" } }

这是我的 tsconfig.json 文件: { "compilerOptions": { "skipLibCheck": true, "moduleResolution": "node" }, "exclude": [ "node_modules" ] }

我在 FunctionFile.ts 的顶部声明了require('core-js');,但错误仍然存​​在。

我遵循了这个问题中提供的指导: Office Addins file in its TypeScript version doesn't work

使用我基于此链接创建的相同加载项: https://docs.microsoft.com/en-us/office/dev/add-ins/develop/convert-javascript-to-typescript

我在我的测试 TypeScript 文件中添加了以下内容:

(function () {
    Office.initialize = function (reason) {
        (window as any).Promise = OfficeExtension.Promise;
    };
})();

async function test() {
    return 'hello';
}

我在构建项目时仍然遇到同样的错误。 “TS2468 TypeScript 找不到全局值‘Promise’。”我也尝试过在顶部使用(window as any).Promise = OfficeExtension.Promise;

【问题讨论】:

标签: typescript visual-studio-2017 es6-promise office-js polyfills


【解决方案1】:

似乎可以通过将以下 lib 属性添加到您的 tsconfig.json 文件的 compilerOptions 对象来解决此问题:

"lib": [ "es5", "dom", "es2015.promise" ]

换句话说,将 ts.config 文件的内容更新为如下所示:

{
  "compilerOptions": {
    "skipLibCheck": true,
    "moduleResolution": "node",
    "lib": [ "es5", "dom", "es2015.promise" ]
  },
  "exclude": [
    "node_modules"
  ]
}

【讨论】:

  • @J Allen -- 感谢您提出这个问题。我们更新了文档以包含有关在 ts.config 中包含 lib 属性的指南:docs.microsoft.com/en-us/office/dev/add-ins/develop/…
  • 这正是我所需要的。像魅力一样工作。再次感谢金!
  • 乐于助人。另外,感谢@MichaelZlatkovsky-Microsoft 与我讨论这个问题......谢谢,迈克尔!
  • @MichaelZlatkovsky-Microsoft -- 仅供参考,将其添加到 tsconfig 文件确实解决了编译器的问题,但它在运行时失败了。我通过将<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script> 添加到 FunctionFile.html 页面来解决这个问题。不确定这是否是绝对最好的方法,但它现在对我有用。
猜你喜欢
  • 2011-05-06
  • 1970-01-01
  • 2011-11-01
  • 2020-09-04
  • 2016-08-08
  • 2017-08-23
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
相关资源
最近更新 更多