It’s not difficult to import CommonJS modules from CommonJS modules or import ES modules from ES Modules. However, it is difficult to combine them. And easily lead to the error “import assignment cannot be used when targeting ECMAScript modules”. This article will show ways to fix errors as well as how to set up your project to work in such situations.
What are the causes?
Modules are a way to organize your code into smaller, more manageable chunks, and apps can integrate code from different apps. For years, there have been strategies to introduce modularity into JavaScript code, and TypeScript together with the ECMAScript specification, provided a standard coding system for JavaScript programs that was flexible enough to work with other formats. TypeScript provides support for creating and using modules with the same syntax as ES module syntax. The cause of the error is that the module you want to import is not a module of ECMAScript. For example, when you execute the command:
Example:
import module = require("module");
Then an error occurs:
Import assignment cannot be used when targeting ECMAScript modules.
Solution for the error “import assignment cannot be used when targeting ECMAScript modules”
Two modules with different syntax and implementations, Javascript and CommonJS can use require()
to import other modules, but import()
can be used to dynamically import modules exception. In addition to ES modules, CommonJS and ES allow users import
with JavaScript modules (i.e. import modules from “modules”).
So to solve the above error, we will add the following code in the file tsconfig.json
{ "compilerOptions": { "module": "commonjs" } }
After adding, remember to restart the console.
In TypeScript we can use many different import methods eg.
Default Import: import module from “module”
Namespace Import: import * as module from “module”
Import Equal: import module = require(“module”)
Dynamic Import: import(“module”).then()
Old Require: const module = require(“module”)
Some downloadable modules, such as AMD and CommonJS, have an attribute called export that contains all the functionality exported by the module. When using one of these built-in modules, the export can be modified by changing the export value. This is the same in ES modules as well as in TypeScript exports.
Summary
Through this article, we know the cause of the error “import assignment cannot be used when targeting ECMAScript modules” and fix it by changing the configuration in the file tsconfig.json
. We hope the article is helpful to you. Thanks for reading.

Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).