简体   繁体   中英

Typescript import for an npm package without a definition

I've got an npm package (@salesforce/canvas-js-sdk) which doesn't have a Typescript definition file for it. I'm using React and so I'm using the "import from" syntax to pull in depenencies. Visual Studio seems to dislike that there isn't a definition file for the module. Also, this module is supposed to expose a property on the "window" object called Sfdc. How can I define a definition file for this npm package without modifying the package?


What I've been attempting:

This is what my current import statements look like.

在此处输入图片说明

I then defined a very simple definition for the module like so.

在此处输入图片说明

That resolves the compilation errors where it couldn't find the module definition. But if I try to use the Sfdc object like in the example it doesn't work.

Here is a picture from the documenation for how to use the library with plain JavaScript. 在此处输入图片说明

But that code doesn't work for me at runtime if I copy and paste it. Instead I can only get a reference to the Sfdc object if I use

在此处输入图片说明

Solution

Because the package was built on a global object, I needed to simplify the import statement. I couldn't just exclude the import because the package code wouldn't be included on the page. 在此处输入图片说明

Then I had to change my d.ts file to declare the Sfdc object globally. 在此处输入图片说明

Given that the module isn't actually a module (it's a global object exposed), you'll want your custom typings to match that.

Instead of declare module '@salesforce/canvas-js-sdk' try writing declare namespace Sfdc .

You should then be able to remove the import statements and access the global Sfdc variable directly from anywhere in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM