我正在阅读有关 ES2015
模块的内容,并试图确保我理解这个新功能。
由于没有像“use strict”
这样的东西,浏览器如何确定 .js 文件是 ES2015
模块而不是 ES2015
模块?一个包含一堆全局变量的 ES5 文件?仅仅是因为存在至少一个“export
”语句吗?
// This file is interpreted as ES5 with globals
function fun1() {...}
function fun1() {...}
// This file is interpreted as ES2015 module
function fun1() {...}
function fun1() {...}
export default function(){...}
最佳答案
Since there's nothing like "use strict", how does the browser determine that a .js file is an ES2015 module v.s. an ES5 file with a bunch of globals? Is it just by the presence of at least one "export" statement?
当你问这个问题时,事情还没有决定,但那是几年后的事了:type
使用属性:
<script type="module" src="./mod.js"></script>
您还需要包含一个路径(不仅仅是src="mod.js"
),除非您使用 import map (截至 2019 年 7 月撰写本文时,这是相对较新的内容,我认为还没有任何浏览器原生支持它们)。
如果您在非模块中使用import
或export
,则会出现语法错误。
在具有自己的类 CommonJS (CJS) 模块系统的 Node.js 中,ECMAScript 模块 (ESM) 以以下两种方式之一表示:
通过在最近的
package.json
中添加"type": "module"
,或者通过为脚本指定扩展名
.mjs
而不是.js
。
(如果最近的 package.json
具有 "type": "module"
,您仍然可以通过给它扩展名 作为 CJS 模块的脚本>.cjs
。)详细信息 here .
关于javascript - ES2015 模块与 ES5 全局变量由 'export' 关键字确定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502315/