简体   繁体   中英

In typescript, how can I import a plain javascript file with a default export using es6 syntax?

Let's say I have a file in my typescript project that I want to be just plain JS, for reasons (not interested in hearing arguments for why that's good or bad).

Example Javascript file (named foo.js):

export default foo = { prop: 'value' }

Typescript file in same folder consuming above Javascript file

import foo from "./foo";

When I do this and try and run the typescript compiler, I get the following error:

error TS7016: Could not find a declaration file for module './foo'. '{fileLocation}/foo.js' implicitly has an 'any' type.

I've read up on the documentation regarding declaration files a bit. In a real-world example, foo's object structure is not simple. and I DO NOT want to define it's structure just to use it in my project for time reasons.

Is there a simple straightforward way to declare this module as type any and move on with my day?

Try putting allowJs in your tsconfig.json file.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["es2015", "dom"],
    "strict": true,
    "esModuleInterop": true,
    "outDir": "dist",
    "allowJs": true 
  }
}

Aside: Your example default export syntax is invalid. Here is a valid example:

export default { prop: 'value' }

Here is a demo for fun .

Make sure to create a typing file foo.d.ts

// foo.d.ts
declare module 'foo';

and set noImplicitAny to false on the tsconfig.json file:

 "noImplicitAny": false, 

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