dts-gen
works by running the code of the module you're targeting and this causes problems for modules that rely on the browser to run (since it runs from a node environment).
The following errors are common in these cases.
ReferenceError: window is not defined
SecurityError: localStorage is not available for opaque origins
The following instructions will help to fix these.
Install dts-gen
as a dependency of the module you're using. Also install jsdom. Later we'll use the local versions of these modules to run the command and prevent polluting the global namespace.
yarn add dts-gen jsdom
Make sure the target module you want is also installed and navigate to this the nodemodules package json.
For my usecase I'm working with storejs
.
yarn add storejs
# If you use vscode and have it set up on your command line run the following.
code node_modules/storejs/package.json
Look for the main key in the package.json.
{
"main": "dist/store.common.js",
}
This is the file that needs to be edited. Open the file and add the following snippet to the top of that file.
const { JSDOM } = require('jsdom');
const DEFAULT_HTML = '<html><body></body></html>';
const jsdom = new JSDOM(DEFAULT_HTML, {
url: "https://www.bbc.co.uk",
referrer: "https://www.bbc.co.uk",
contentType: "text/html",
userAgent: "node.js",
includeNodeLocations: true
});
const { window } = jsdom;
const { document, navigator } = window;
Finally run the following to generate the types.
yarn dts-gen -m storejs
This will create a storejs.d.ts
file in the package root.
You can now safely remove dts-gen
and (optional) jsdom
from your dependencies.
yarn remove dts-gen jsdom