SyntaxError: Unexpected token import in Node.js and TS

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
4 min

banner

# Table of Contents

  1. SyntaxError: Unexpected token import in Node.js
  2. Unexpected token import Error in TypeScript

If you got the error when using TypeScript, click on the second subheading.

# SyntaxError: Unexpected token import in Node.js

The "SyntaxError: Unexpected token import" occurs when we use the ES6 import syntax in a version of Node that doesn't support it.

To solve the error, use the require syntax, e.g. const myPackage = require('my-package') or set the type attribute to module in your package.json file.

Here is an example of how the error occurs.

index.js
import {sum} from './another-file'; import somePackage from 'some-package' /** * import {sum} from './another-file'; ^^^^^^ SyntaxError: Unexpected token import */

To solve the error, replace your ES6 modules import with a require import that is supported in your version of Node.js.

index.js
// ๐Ÿ‘‡๏ธ named import for local file (relative path) const {sum} = require('./another-file'); // ๐Ÿ‘‡๏ธ default import for 3rd party package (absolute path) const somePackage = require('some-package');

Using the require CommonJS modules syntax will solve the error.

If you prefer to use the ES6 modules syntax, set the type attribute to module in your package.json file.

package.json
{ "type": "module", // ๐Ÿ‘‡๏ธ rest ... }

setting type to module in package json

If you don't have a package.json file, initialize one using the npm init -y command in the root directory of your project.

Now you can use ES6 modules syntax in your Node.js application.

index.js
import _ from 'lodash'; import express from 'express'; // ๐Ÿ‘‡๏ธ import from local file (INCLUDE EXTENSION!!!) import {sum} from './another-file.js'; console.log(_.uniq([1, 1, 3])); // ๐Ÿ‘‰๏ธ [1, 3] console.log(sum(10, 10)); // ๐Ÿ‘‰๏ธ 20 console.log(express);

When you import local files and have set the type attribute to module, you must include the .js extension.

index.js
import {sum} from './another-file.js'; console.log(sum(25, 25)); // ๐Ÿ‘‰๏ธ 50

If you omit the extension, you will get an error - "Error [ERR_MODULE_NOT_FOUND]: Cannot find module X".

The error occurs if try to run your source files that contain the ES6 module import/export syntax, instead of running your compiled files from your build directory.

Make sure to run your compiled files from your build/dist directory only.

# Unexpected token import Error in TypeScript

To solve the "Uncaught SyntaxError: Unexpected token import" in TypeScript, set the module option to commonjs in your tsconfig.json file and make sure to compile your TypeScript files (e.g. with ts-node), and not to run them directly with node.

Open your tsconfig.json file and make sure the module option is set to commonjs.

tsconfig.json
{ "compilerOptions": { "target": "es6", "module": "commonjs", "esModuleInterop": true, // ... rest } }

The module option sets the module system for the program.

The esModuleInterop option is set to false by default, which causes it to treat CommonJS modules similar to ES6 modules. This causes some issues.

Setting esModuleInterop to true fixes these issues.

# Trying to run a TypeScript file directly with node

Another common cause of the error in TypeScript is trying to run a TypeScript file directly with node, e.g. node src/index.ts.

This doesn't work, because we first have to transpile the file to JavaScript before we run it with node.

The same is the case if you have incorrectly configured your TypeScript project that uses babel or ts-node.

Are your TypeScript files getting transpiled to JavaScript files in your build directory? Your build directory should only contain JavaScript files. If it contains TypeScript files, you have configured your project incorrectly.

# Set module to commonjs in your tsconfig.json file

If your project uses ts-node, you can try to add an override that sets module to commonjs in your tsconfig.json file.

tsconfig.json
{ "ts-node": { // these options are overrides used only by ts-node "compilerOptions": { "module": "commonjs" } }, "compilerOptions": { // ... rest of your ts options }, }

Another thing you should check is that the main property in your package.json file points to your index.js file, and not your index.ts file.

Also, make sure your Node.js version on the specific machine is recent. It's best to use the LTS version and to avoid using obsolete versions.

Take a look at your build folder, which you've set via the outDir option in your tsconfig.json file. Your config could be wrong and you could still be producing TypeScript files in your build directory.

# An example working config for a ts-node project

If none of the suggestions above work, take a look at a working config for a TypeScript project that uses ts-node.

This is my tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "skipLibCheck": true, "target": "es6", "module": "commonjs", "moduleResolution": "node", "allowJs": true, "resolveJsonModule": true, "esModuleInterop": true, "outDir": "./build", "rootDir": "src", }, "include": ["src/**/*"], "exclude": ["node_modules"] }

Make sure the include array points to a directory that contains all of the necessary files for your project.

This is my package.json file.

package.json
{ "name": "example", "version": "1.0.0", "main": "build/index.js", "scripts": { "build": "rimraf ./build && tsc", "dev": "nodemon", "start": "npm run build && node build/index.js", }, "devDependencies": { "@types/node": "^17.0.21", "nodemon": "^2.0.15", "rimraf": "^3.0.0", "ts-node": "^10.4.0", "typescript": "^4.6.2" } }

And here is the nodemon.json configuration file which is located in the same directory.

nodemon.json
{ "watch": ["src"], "ext": ".ts,.js", "ignore": [], "exec": "ts-node --files ./src/index.ts" }
This project structure assumes that you place all of your TypeScript files in a directory called src and have an index.ts entry point under src/index.ts.

The ts-node package will transpile your code to JavaScript and run it with node.

Your build files will be in the build directory. Note that your build directory shouldn't contain any TypeScript files, it should only contain JavaScript files.

If your build directory contains TypeScript files, you have a configuration error in your project.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev