在Node中使用Es6的import
安装必须的包
npm install @babel/core @babel/register @babel/preset-env --save-dev
2. 创建文件
// file server.js
const express = require('express')
const app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
将require替换成import
// file server.js
import express from 'express'
const app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
3. 增加start.js文件
// file start.js
// Transpile all code following this line with babel and use '@babel/preset-env' (aka ES6) preset.
require("@babel/register")({
presets: ["@babel/preset-env"]
});
// Import the rest of our application.
module.exports = require('./server.js')
4. 运行文件
node start.js
最后更新于
这有帮助吗?