繁体   English   中英

在Expressjs,Node中使用ES6功能

[英]Using ES6 features in Expressjs, Node

因此,我一直在尝试在Express中使用ES6功能。 我读到Node.js现在已经本机支持es6,所以我不需要babel为我做任何事情。

在我的app.js文件中,我有:

'use strict';

const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const mongoose = require('mongoose');
const shell = require('shelljs');
const fs = require('fs'), gm = require('gm');
const routes = require('./routes/index');
const users = require('./routes/users');
const app = express();
// view engine setup
// app.use(express.static(__dirname + '/bundle'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
// app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use((err, req, res, next) => {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
module.exports = app;

然后,我得到了server.js文件,该文件基本上只运行http服务器,并指向我的app.js server.js文件中没有错误。 但是,我在那里使用es5。

Path/To/Project/app.js:3
const express = require('express');
^^^^^
SyntaxError: Use of const in strict mode.
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (Path/To/Project/server.js:7:11)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
NAME-MacBook-Pro% 

我删除了'use strict'; 从文件的顶部开始抱怨,但是出现另一个错误,带有unexpected token

我需要使用babel来编译它吗? 为什么抱怨呢?

谢谢!

我认为您使用的是旧版本的节点。 您必须具有4+版本才能使用ES6功能(例如const

如果需要使用es6的所有功能,最好先使用babel进行编译。 截至目前,即使Node v5.0.0仅实现59%的ES6功能。

检查链接以获取ES6兼容性表。

const仍然会继续抱怨,即使在ES6中const也已作为块作用域提供。 并且您正在块外部使用它。

请通过了解更多详情

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM