Node.js - SyntaxError: Unexpected token import
To quickly and effectively fix the SyntaxError: Unexpected token import in Node.js:
-
Apply
require()instead ofimport: -
Enable ES Modules in Node.js v14+:
Either:
-
Rename files to
.mjs -
or add
"type": "module"inpackage.json, enabling use ofimport:
Then use
importas shown below: -
-
Utilize Babel to transpile:
- Install Babel:
- Create
.babelrc:
- Run Babel:
Choose the solution that matches your Node.js version and project requirements for an instant fix.
Deep dive into solutions
Leveraging 'esm' for seamless 'import'
If an upgrade to Node.js v14+ is not feasible but import syntax is still desired:
-
Install the
esmpackage to bridge the syntax gap: -
Modify your
package.jsonstart script to support-r esm:
Bridging the gap between ES Modules and CommonJS
In scenarios where import and require are mixed or when transitioning between the two:
- Swap
export defaultwithmodule.exportswhen importing a module in the CommonJS style. - Utilize the
import()syntax for dynamic interpretations that comply with CommonJS. - Be aware that named imports require deconstruction from
module.exports. - In short, bridge the 'import' and 'require' worlds sensibly to avoid syntax hiccups.
Babel: transpilation station for ES syntax in Node.js
To establish a server-side Node.js environment with Babel for an "ES6 today, run anywhere" experience:
-
Install
babel-cliglobally for command-line access: -
Favor
babel-preset-envfor targeting specific environments: -
Update the
startscript to run Node.js with Babel transpiling:
Ensure to regularly review updated Node.js help documents and MDN compatibility tables to stay on top of module import support.
Was this article helpful?