Introduction
The import
syntax is specific to ES6 Modules(introduced in ES2015) since JavaScript never had a package system besides the old <script></script>
.
Nodejs uses Commonjs Pattern adopted as the de facto standard for using modules in Nodejs applications.
All code for this example can be found in: this repo
Using the import
syntax
The import
syntax is pretty intuitive. The syntax for import
is:
// default
import utils from './utils'
// non-default multiple exports
import {parser, reader } from './utils'
Here’s how we can use the same syntax in Nodejs:
- In your
package.json
, add"type"
:"module"
{
"name": "node-js-import-syntax",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"type": "module",
"scripts": {
"start": "node src/index.js"
}
}
- Use the
import/export
syntax as you would in ES6 Modules:
import express from 'express'
// Note: remember to include the file extension (.js) for this to work!
import indexRouter from './router.js'
const app = express()
const PORT = process.env.PORT || 3000
// enable JSON parsing middleware to parse json.
app.use(express.json())
app.use('/index', indexRouter)
async function main() {
app.listen(PORT, () => console.log('HTTP server up at PORT'))
}
main().catch((err) => console.error(err))
Inside router.js
module:
import { Router } from 'express'
// create an Instance of the Router
const indexRouter = Router()
indexRouter.get('/', (req, res) => {
res.json({ message: 'Hello Champ!' })
})
export default indexRouter
That’s how easy to use the import/export
syntax in a Nodejs codebase!
Follow me on twitter @nkmurgor where I tweet about interesting topics.