我在Windows上安装了官方节点js版本v5.9.1(x64),并尝试使用ECMAScript对类进行一些操作。我写了一个简单的类来测试:
"use strict";
export class httpWrapper {
getPage(options){
// some code
}
};
我将这个课程放在httpWrapper.js
中。正如你可以看到我使用导出这里导出类。然后我用这段代码创建了'main.js':
'use strict';
import httpWrapper from 'httpWrapper';
let theInstance = new httpWrapper();
当我运行node main.js
时,我收到错误:
import httpWrapper from 'httpWrapper';
^^^^^^
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:142:18)
at node.js:939:3
我还试图用节点运行httpWrapper.js
,我得到了:
export class httpWrapper {
^^^^^^
SyntaxError: Unexpected token export
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:142:18)
at node.js:939:3
节点js中的导入/导出功能是否可用?因为这些语句不起作用,我不能使用导出/导入,你怎么想导出/导入类?
答案 0 :(得分:0)
现在浏览器不了解ES6(ECMAScript2015)你需要使用像babel那样将ES6转换为ES5的转换器。
答案 1 :(得分:-1)
您需要安装npm install babel-cli -g
,然后运行babel-node main.js
或者如果您需要运行节点,则需要使用require hook babel-register创建js。
示例:
// runner.js
// I implement async in my modules, for this reason i need the preset stage-3 & es2015-node to support es6 features
require("babel-register")({
presets: ['es2015-node', 'stage-3']
});
// Import you main module with require and run
// On this example I export http.createServer on server.js -> export default server
var server = require('./server.js')
server.listen(3000, function () {
console.log('Server running')
})
// Server.js
import express from 'express'
import { Server } from 'http'
import bodyParser from 'body-parser'
import morgan from 'morgan'
var app = express()
// configuracion
app.use(morgan('combined'))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.set('view engine', 'jade')
// Route para nuestra API
var router = express.Router()
router.get('/', function (req, res) {
res.json({ message: 'hooray! welcome to our api!' })
})
app.use('/api', router)
var server = Server(app) // require('http').createServer(app.callback())
// app.listen(3000)
console.log('Magic happens on port 3000')
export default server
现在只运行node runner.js
有时需要添加标志--harmony