Tag Archives: SyntaxError: Unexpected token import

[Two Solutions] Syntax error: unexpected token import

The module import/export ( Import/export ) function of ES6 syntax, when we use it, we may report an error:

SyntaxError: Unexpected token import
Syntax error: unexpected token import

The situation I encountered was caused by the Import syntax not being recognized. Here, there are two solutions

1: Using the V8 and later versions of node

Because the ECMAScript modules and imort syntax are only supported in the version after V8. X. at present, the stable version of node is v8.11.2. You can use NVM to install and manage multiple node versions

You can use the -- experimental modules experimental module flag to enable the feature of loading ECMAScript modules. Moreover, the file name loaded as ES module must end with . MJS suffix

node --experimental-modules my-app.mjs

This method will prompt when outputting:

(node:16208) ExperimentalWarning: The ESM module loader is experimental.

It means an experimental module, which may be modified at that time. example: https://github.com/weiqinl/demo/tree/master/01-es6-import

2: Using Babel, general method

The browser directly supports Import to a low degree, so Babel is needed to convert Import to Es5 syntax

Installation

Through NPM:

npm install --save-dev babel-preset-env babel-cli

Or through yarn:

yarn add babel-preset-env --dev

Use

Default behavior without options will run all transforms (same as Babel preset latest ). Create a new . Babelrc file and write:

{
    "presets": ["env"]
}

Implementation

babel-node index.js

My example: https://github.com/weiqinl/demo/tree/master/01-es6-import An example given by Babel official: https://github.com/babel/example-node-server

Updated on October 18, 2018

Unable to recognize Import , another way of thinking, it can also be said that low version browsers do not support it. Now Babel has been updated to version 7, we use the latest Babel to implement. The solution of babel7 to this problem is as follows: https://www.cnblogs.com/weiqinl/p/9773048.html

Reference: https://github.com/nodejs/help/issues/53