Node.Js - Syntaxerror: Unexpected Token Import

Node.js - SyntaxError: Unexpected token import

Node 13+ Since Node 13, you can use either the .mjs extension, or set {"type": "module"} in your package.json. You don't need to use the --experimental-modules flag. Modules is now marked as stable in node.js

Node 12 Since Node 12, you can use either the .mjs extension, or set "type": "module" in your package.json. And you need to run node with the --experimental-modules flag.

Node 9 In Node 9, it is enabled behind a flag, and uses the .mjs extension.

node --experimental-modules my-app.mjs

While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.

See browser compat table on MDN and this Node issue.

From James M Snell's Update on ES6 Modules in Node.js (February 2017):

Work is in progress but it is going to take some time — We’re currently looking at around a year at least.

Until support shows up natively (now marked stable in Node 13+), you'll have to continue using classic require statements:

const express = require("express");

If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel. Here's an example server.

Unexpected token import express js

By default, node.js does not support ECMAScript's import statements, so instead of writing import isEmpty from './is-empty'; you should write const isEmpty = require('./is-empty');.

If you prefer to use import statements, you can enable ECMAScript Modules support by adding --experimental-modules argument to Node. But please be aware that their support is still experimental and it is not recommended to use them in production environments. In your case, you'll need to edit the package.json file of your project and replace start script command to:

node --experimental-modules ./server.js

SyntaxError: Unexpected token import - Express

NodeJS supports import natively only experimentally, and only if your script has the .mjs extension.

That's why the start in your package.json is referring to babel-node, which transpiles ES6 code into classic JS on-the-fly before running it. But I doubt even that command will work, because you're not passing any presets to babel to run the script. Try this command:

nodemon --exec babel-node --presets env index.js

[OR]

Rename your file to have .mjs extension, then run this:

nodemon --experimental-modules index.mjs

Node.js - SyntaxError: Unexpected token '{'

Imports can only be at the very top level. They're hoisted (above all other non-import statements), and cannot be in blocks or conditionals.

You'll need something like

import * as prod from './prod';
import * as dev from './dev';

const obj = process.env.NODE_ENV === 'production' ? prod : dev;
const { googleClientID, googleClientSecret, mongoURI, cookieKey } = obj;

export { googleClientID, googleClientSecret, mongoURI, cookieKey }


Related Topics



Leave a reply



Submit