I am working on a AngularJS project using typescript. I am trying to use the js-xlsx
library to parse an xlsx file and I get the compile error:
error TS2304: Cannot find name 'XLSX'
We are using a global namespace for all files and all the compiled files get concatenated because of the outFile
compiler option. No module system is configured and we include all our JavaScript dependencies in the index.html
file. We therefore do not import
any modules.
All other dependencies up to this point have type definitions installed under node_modules/@types
and are correctly recognized by the compiler as explained here.
The js-xlsx
however includes the type definitions in the package, i.e node_modules/xlsx/types/index.d.ts
but this is not automatically picked up by the compiler.
Unfortunately I cannot change the project structure and module system. How do I get the typescript compiler to recognize the type definitions of the xlsx
package so that I can do:
onload(event: any) {
let workbook = XLSX.read(event.target.result, {type: "binary"});
}
without getting compiler errors and get intellisense/code completion in VS Code.
You can create a global definition that exposes the module as a global variable.
Save the index.d.js
in any location in your project as js-xlsx.d.ts
In the same location add a file js-xlsx-global.d.ts
import * as xlsx from './js-xlsx'
declare global {
export var XLSX: typeof xlsx;
}
Now you can use ///
references in files to get the XLSX
variable to type correctly
/// <reference path="./js-xlsx-global.d.ts" />
XLSX.read(null, { type: "binary"}); // works, and is checked.