javascript - ES2015 模块与 ES5 全局变量由 'export' 关键字确定?

标签 javascript ecmascript-6

我正在阅读有关 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 月撰写本文时,这是相对较新的内容,我认为还没有任何浏览器原生支持它们)。

如果您在非模块中使用importexport,则会出现语法错误。


在具有自己的类 CommonJS (CJS) 模块系统的 Node.js 中,ECMAScript 模块 (ESM) 以以下两种方式之一表示:

  1. 通过在最近的 package.json 中添加 "type": "module",或者

  2. 通过为脚本指定扩展名 .mjs 而不是 .js

(如果最近的 package.json 具有 "type": "module",您仍然可以通过给它扩展名 作为 CJS 模块的脚本>.cjs。)详细信息 here .

关于javascript - ES2015 模块与 ES5 全局变量由 'export' 关键字确定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502315/

相关文章:

javascript - AngularJs 和 Google map 问题 : Not displaying markers?

javascript - 如何识别鼠标悬停事件对象是否来自触摸屏触摸?

javascript - 根据键确定对象数组是否包含条目

javascript - 在表格行中添加垂直滚动

javascript - 按两个标准对多维数组进行排序?

javascript - JS reducer : return combined array of objects

javascript - 如何在 normalizr 中为同一实体设置多个标识符?

javascript - 在 ES6 Set 中存储数组并按值访问它们

javascript - Canonical 更新为 JS - 这是 SEO 使用的吗?

javascript - 将当前日期与从 api 响应中收到的日期进行比较