【问题标题】:Using 'require' with esm - ReferenceError: require is not definedUsing \'require\' with esm - ReferenceError: require is not defined
【发布时间】:2022-12-01 12:48:25
【问题描述】:
I have been updating my codebase to replace instances of 'require' with import syntax as per esm guidelines, but have hit a snag with a few examples where I'm not sure what the correct syntax is:
const router = require('express').Router();
require('dotenv').config();
What is the correct way to convert these to import syntax?
【问题讨论】:
标签:
javascript
node.js
express
es6-modules
【解决方案1】:
You can get a reference to express router by first importing the express package
import express from "express";
and then accessing the Router property on it
const router = express.Router();
You can do the similar thing for dotenv package.
// import the "dotenv" package
import dotenv from "dotenv";
// call the config function
dotenv.config();