kennethjiang/js-file-download

Importing in TypeScript

Closed this issue · 6 comments

What is the proper way to import the module in typescript?
The definition file suggests that it's a default export, however, TypeScript interprets that as having module.default, which this module does not in fact have. With the current definition file, the only way to get typed and working function is this:

import * as fileDownload_ from 'js-file-download';
const fileDownload = fileDownload_ as any as typeof fileDownload_.default;

Using default import returns undefined.

import fileDownload from 'js-file-download';
fileDownload === undefined // true

I use it like this: import fileDownloader from 'js-file-download';

Maybe there is a problem with your configuration

Let's compare tsconfig.json for now:

{
    "compilerOptions": {
        /* Basic Options */
        "target": "es3", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
        "module": "commonjs", /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
}

@rsxdalv , here's a tsconfig.json that I'm using in a simple "Hello World" test app.

{
  "compilerOptions": {
    "strict": true,
    "module": "commonjs",
    "jsx": "preserve",
    "esModuleInterop": true,
    "sourceMap": true,
    "allowJs": true,
    "lib": [
      "es6",
      "dom"
    ],
    "rootDir": "src",
    "moduleResolution": "node"
  }
}

index.ts:

import fileDownload from "js-file-download";

document.getElementById("downloadButton")!.onclick = () => {
  fileDownload("Hello World!", "hello_world.txt");
};

Thank you, it seems that --esModuleInterop is the change, my tsconfig file was so old it didn't even have it.
I'll test it and close this if enabling this setting causes no problems.

Seems to be the way to go, since all of my newly generated tsconfigs include it by default.