39

I'm trying to import express into the project and in the middle of the development, it just stopped working, i've reseted configurations, etc. Can't make it work, can't import any modules.

npx tsc src/server.ts 
src/server.ts:1:8 - error TS1259: Module '"/home/fpc-ubut/Git/nlw2/server/node_modules/@types/express/index"' can only be default-imported using the 'esModuleInterop' flag

1 import express from 'express';
src/database/migrations/00_create_users.ts:1:8 - error TS1259: Module '"/home/fpc-ubut/Git/nlw2/server/node_modules/knex/types/index"' can only be default-imported using the 'esModuleInterop' flag

1 import Knex from 'knex'
src/server.ts:1:8 - error TS1259: Module '"path"' can only be default-imported using the 'esModuleInterop' flag

1 import path from 'path'

Enviroment OS: Ubuntu 20.04.1 LTS
node: v12.18.1
packages:

    "@types/express": "^4.17.6",
    "@types/node": "^14.0.27",
    "ts-node": "^8.10.2",
    "ts-node-dev": "^1.0.0-pre.44",
    "typescript": "^3.9.3"

    "express": "^4.17.1",
    "knex": "^0.21.1",
    "pg": "^8.2.1"

EDIT1: as asked, here is my tsconfig.json. But the configuration ("esModuleInterop": true), is already as aspected

<tsconfig.json>


    {
      "compilerOptions": {
        /* Visit https://aka.ms/tsconfig.json to read more about this file */
    
        /* Basic Options */
        // "incremental": true,                   /* Enable incremental compilation */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        // "lib": [],                             /* Specify library files to be included in the compilation. */
        // "allowJs": true,                       /* Allow javascript files to be compiled. */
        // "checkJs": true,                       /* Report errors in .js files. */
        // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
        // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
        // "sourceMap": true,                     /* Generates corresponding '.map' file. */
        // "outFile": "./",                       /* Concatenate and emit output to single file. */
        // "outDir": "./",                        /* Redirect output structure to the directory. */
        // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        // "composite": true,                     /* Enable project compilation */
        // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
        // "removeComments": true,                /* Do not emit comments to output. */
        // "noEmit": true,                        /* Do not emit outputs. */
        // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
        // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
        // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    
        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */
        // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
        // "strictNullChecks": true,              /* Enable strict null checks. */
        // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
        // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
        // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
        // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
    
        /* Additional Checks */
        // "noUnusedLocals": true,                /* Report errors on unused locals. */
        // "noUnusedParameters": true,            /* Report errors on unused parameters. */
        // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    
        /* Module Resolution Options */
        // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
        // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
        // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
        // "typeRoots": [],                       /* List of folders to include type definitions from. */
        // "types": [],                           /* Type declaration files to be included in compilation. */
        // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
        // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
        // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */
    
        /* Source Map Options */
        // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
        // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
        // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
    
        /* Experimental Options */
        // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
    
        /* Advanced Options */
        "skipLibCheck": true,                     /* Skip type checking of declaration files. */
        "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
      }
    }

EDIT 2: Changed tsconfig.json "allowSyntheticDefaultImports": true Still showing the same error

EDIT 3: Github link: [REMOVED]

the problem is on ./server ./server2 is working just fine. Same configs.

EDIT4: RESOLVED

According to your GitHub repo, ./server does NOT have a tsconfig file while .server2 does have one.. If I need to be more clear: they do not have the same config, because server does not even have a config. You should move ./server/src/tsconfig.json to ./server/tsconfig.json, just like your tsconfig file is in ./server2 (notice I said MOVE not COPY the tsconfig).. – Matt Oestreich

7
  • 1
    Showing your tsconfig.json file is going to be more important than your package.json... Perhaps, this may help? Commented Aug 8, 2020 at 21:53
  • So what changed then? Was your tsconfig.json file recently modified? Did you change the import statements? Have you tried basic troubleshooting? PLEASE help people help you. Commented Aug 8, 2020 at 22:31
  • 1
    According to your GitHub repo, ./server does NOT have a tsconfig file while .server2 does have one.. If I need to be more clear: they do not have the same config, because server does not even have a config. You should move ./server/src/tsconfig.json to ./server/tsconfig.json, just like your tsconfig file is in ./server2 (notice I said MOVE not COPY the tsconfig).. Commented Aug 8, 2020 at 22:35
  • 1
    FranciscoPena, please try this: You should move ./server/src/tsconfig.json to ./server/tsconfig.json, just like your tsconfig file is in ./server2 (notice I said MOVE not COPY the tsconfig).. Commented Aug 8, 2020 at 22:38
  • 1
    FranciscoPena haha no worries - we all make mistakes and overlook the little things sometimes. I went ahead and added an official answer, so please make sure to mark it as the accepted answer if my solution resolved your issue. Commented Aug 8, 2020 at 22:48

10 Answers 10

47

In my case, I was facing this error for react. I fixed it by changing my import style from

import React from 'react';

to

import * as React from 'react';
Sign up to request clarification or add additional context in comments.

2 Comments

Same here (not using React). The reason this is the best solution is that JSON files don't have a default export, so you need to specify a name during import.
Mine threw a hissy fit and demanded the exact opposite. Was importing Express with the * anonymous identifier and Typescript demanded it to be named instead. At least it all worked out in the end.
26

As the error states, you need the set

"esModuleInterop": true,

in your tsconfig.json file. This allows default imports from modules with no default export.

7 Comments

My tsconfig.json already shows the config <tsconfig.json> "esModuleInterop": true
how about setting allowSyntheticDefaultImports to true?
Changed it: "allowSyntheticDefaultImports": true, still showing the error
put this under "compilerOptions": {"esModuleInterop": true,)
also using tsc -p . package.json { scripts: { "compile": "tsc -p ."} }
|
8

tsconfig.json

{
  "compilerOptions": {
    "esModuleInterop": true,
  }
}

Comments

7

According to your GitHub repo, you have the following structure (some files/directories have been omitted):

Bad:

  • server
    • src
      • tsconfig.json
  • server2
    • src
    • tsconfig.json

You will need to move /server/src/tsconfig.json to /server/tsconfig.json - please note that you will need to MOVE, not COPY the tsconfig file.

Good:

  • server
    • src
    • tsconfig.json
  • server2
    • src
    • tsconfig.json

Comments

3

Write only tsc instead of tsc <filename> in Terminal

2 Comments

What do you mean by "only tsc"?
Only solution that worked but why this work? because typescript will automatically look into "*.ts" and transpile it?
2

You can add "allowSyntheticDefaultImports": true to the compilerOptions block in the tsconfig.node.json file to fix this error.

For example,

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true
  }
}

Comments

0

Solved. Add this three in compilerOptions, Because using this method esmodule can still be used in it basic way "import express from 'express' and have access to Request and Response.

import express, { Request, Response } from 'express'
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"verbatimModuleSyntax": false,

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has a few answers—including at least one that has been validated by the community. It would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?
-1
import express = require("express")

This resolved my problem after reading the error log which stated (that this module is declared using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.)

From there, I checked the declaration files at node_modules/@types/express/index.d.ts:133:1 and its usage is within the comments section shown here:Comment section of the @types/express/index.d.ts

Comments

-1

]If you add just one line then this issue will solve.

Before solution try to understand as a developer why this error occurred.

  • The error message suggests that you need to enable the 'esModuleInterop' flag in your TypeScript configuration. So, you have to just make esModuleInterop: true

To fix this issue

Just open your tsconfig.json file and add this line to compilerOptions option.

You can copy this code and past to your tsconfig.json file.

{
  "compilerOptions": {
    "target": "es5",
    "module": "CommonJS",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

Comments

-1

Update the tsconfig as bellow and it works for me;

  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "esModuleInterop": true,                                                
    "forceConsistentCasingInFileNames": true,  
    /* Type Checking */
    "strict": true,    
  },
    "include": ["src/**/*.ts"],
    "exclude": ["node_modules"],

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.