kennethjiang / js-file-download

MIT License
918 stars 119 forks source link

Importing in TypeScript #71

Closed rsxdalv closed 3 years ago

rsxdalv commented 3 years ago

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
rsxdalv commented 3 years ago

67

fama1024 commented 3 years ago

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

Maybe there is a problem with your configuration

rsxdalv commented 3 years ago

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'. */
}
kindrowboat commented 3 years ago

@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");
};
rsxdalv commented 3 years ago

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.

rsxdalv commented 3 years ago

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