语法错误:在严格模式下使用 const [英] SyntaxError: Use of const in strict mode
问题描述
我正在使用 node.js,在我的一个 js 文件中,我在 严格模式"
中使用了 const
.尝试运行它时,我收到一个错误:
I'm working with node.js, and in one of my js files I'm using const
in "strict mode"
. When trying to run it, I'm getting an error:
SyntaxError: Use of const in strict mode.
这样做的最佳做法是什么?
What is the best practice to do this?
'use strict'
const MAX_IMAGE_SIZE = 1024*1024; // 1 MB
推荐答案
const
和 let
是 ECMAScript 2015(又名 ES6 和 Harmony)的一部分,而不是在 Node.js 0.10 或 0.12 中默认启用.自 Node.js 4.x 起,V8 认为稳定的所有交付 [ES2015] 功能在 Node.js 上默认开启,不需要任何类型的运行时标志.".Node.js 文档概述了默认启用哪些 ES2015 功能以及哪些需要运行时标志.因此,通过升级到 Node.js 4.x 或更高版本,错误应该会消失.
The const
and let
are part of ECMAScript 2015 (a.k.a. ES6 and Harmony), and was not enabled by default in Node.js 0.10 or 0.12. Since Node.js 4.x, "All shipping [ES2015] features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag.". Node.js docs has an overview of what ES2015 features are enabled by default, and which who require a runtime flag. So by upgrading to Node.js 4.x or newer the error should disappear.
在 Node.js 0.10 和 0.12 中启用一些 ECMAScript 2015 特性(包括 const
和 let
);使用和声标志启动您的节点程序,否则您将收到语法错误.例如:
To enable some of the ECMAScript 2015 features (including const
and let
) in Node.js 0.10 and 0.12; start your node program with a harmony flag, otherwise you will get a syntax error. For example:
node --harmony app.js
这完全取决于您的严格js位于哪一边.我建议在服务器端使用带有 const
声明的严格模式,并使用和声标志启动服务器.对于客户端,您应该使用 Babel 或类似工具将 ES2015 转换为 ES5,因为并非所有客户端浏览器都支持 const代码> 声明.
It all depends on which side your strict js is located. I would recommend using strict mode with const
declarations on your server side and start the server with the harmony flag. For the client side, you should use Babel or similar tool to convert ES2015 to ES5, since not all client browsers support the const
declarations.
这篇关于语法错误:在严格模式下使用 const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!