When I was started with express always wanted a solution to use import instead require
const express = require["express"];
// to
import express from "express"
Many time go through this line:- Unfortunately, Node.js doesn't support ES6's import yet.
Now to help other I create new two solutions here
1] esm:-
The brilliantly simple, babel-less, bundle-less ECMAScript module loader. let's make it work
yarn add esm / npm install esm
create start.js or use your namespace
require = require["esm"][module/*, options*/]
// Import the rest of our application.
module.exports = require['./src/server.js']
// where server.js is express server start file
Change
in your package.josn
pass path of start.js
"scripts": {
"start": "node start.js",
"start:dev": "nodemon start.js",
},
"dependencies": {
+ "esm": "^3.2.25",
},
"devDependencies": {
+ "nodemon": "^1.19.2"
}
2] Babel js:-
This can be divide into 2 part
a] Solution 1 thanks to timonweb.com
b] Solution 2
use
Babel 6 [older version of babel-preset-stage-3 ^6.0] create .babelrc
file at your root folder
{
"presets": ["env", "stage-3"]
}
Install babel-preset-stage-3
yarn add babel-cli babel-polyfill babel-preset-env bable-preset-stage-3 nodemon --dev
Change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build"
},
"devDependencies": {
+ "babel-cli": "^6.26.0",
+ "babel-polyfill": "^6.26.0",
+ "babel-preset-env": "^1.7.0",
+ "babel-preset-stage-3": "^6.24.1",
+ "nodemon": "^1.19.4"
},
Start your server
yarn start / npm start
Oooh no we create new problem
regeneratorRuntime.mark[function _callee[email, password] {
^
ReferenceError: regeneratorRuntime is not defined
This error only come when you
use async/await in your code. Then use polyfill that includes a custom regenerator runtime and core-js. add on top of index.js
import "babel-polyfill"
This allow you to use async/await
use Babel 7
Need to upto date every thing in your project let start with babel 7 .babelrc
{
"presets": ["@babel/preset-env"]
}
Some change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build",
....
}
"devDependencies": {
+ "@babel/cli": "^7.0.0",
+ "@babel/core": "^7.6.4",
+ "@babel/node": "^7.0.0",
+ "@babel/polyfill": "^7.0.0",
+ "@babel/preset-env": "^7.0.0",
+ "nodemon": "^1.19.4"
....
}
and use import "@babel/polyfill"
on start point
import "@babel/polyfill"
import express from 'express'
const app = express[]
//GET request
app.get['/', async [req, res] {
// await operation
res.send['hello world']
}]
app.listen[4000, [] => console.log['🚀 Server listening on port 400!']]
Are you thinking why start:dev
Seriously.
It is good question if you are new. Every change you are boar with start server every time then use yarn start:dev
as development server every change restart server automatically for more on nodemon
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.
Copied!
import {sum} from './another-file'; import somePackage from 'some-package' /** * import {sum} from './another-file'; ^^^^^^ SyntaxError: Cannot use import statement outside a module */
To solve the error, replace your ES6 modules import with a require
import that is supported in your version of Node.js.
Copied!
// 👇️ 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.
Copied!
{ "type": "module", // 👇️ rest ... }
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.
Copied!
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.
Copied!
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 "SyntaxError: Unexpected token import" also occurs if try to run your source files that contain 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.
Conclusion #
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.