How to Polyfill Promise in Visual Studio 2017 Offi

2019-08-05 14:34发布

I am using TypeScript in an Office Add-in, and I want to use async / await functions specifically. The project fails to compile with "TS2468 TypeScript Cannot find global value 'Promise'."

I have read on here that I have to create a polyfill for Promise, but so far have not been able to figure out how to get a polyfill working in Visual Studio 2017. I am attempting to use core-js, and have installed it in to the project using npm install core-js. I can see core-js is installed under node_modules. npm also created a package.json file with the following:

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

Here is my tsconfig.json file: { "compilerOptions": { "skipLibCheck": true, "moduleResolution": "node" }, "exclude": [ "node_modules" ] }

I have require('core-js'); declared at the top of FunctionFile.ts, but the error persists.

I followed the guidance provided in this question : Office Addins file in its TypeScript version doesn't work

Using the same add-in I created based on this link: https://docs.microsoft.com/en-us/office/dev/add-ins/develop/convert-javascript-to-typescript

I added the following to my test TypeScript file:

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

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

I still get the same error when building the project. "TS2468 TypeScript Cannot find global value 'Promise'." I also tried it with (window as any).Promise = OfficeExtension.Promise; at the top.

1条回答
疯言疯语
2楼-- · 2019-08-05 14:57

Seems like this can be resolved by adding the following lib property to the compilerOptions object your tsconfig.json file:

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

In other words, update the contents of your ts.config file to look like this:

{
  "compilerOptions": {
    "skipLibCheck": true,
    "moduleResolution": "node",
    "lib": [ "es5", "dom", "es2015.promise" ]
  },
  "exclude": [
    "node_modules"
  ]
}
查看更多
登录 后发表回答