ES6模块化

113 阅读1分钟
  • es6模块化

    • 每个 js 文件都是一个独立的模块
    • 导入其它模块使用 import 关键字
    • 向外共享模块使用 export 关键字
  • commonJS规范(nodejs)

    • 导入其它模块使用 require关键字
    • 向外共享模块使用 module.exports关键字

    在nodejs中搭建学习es6模块化的环境

让nodejs支持ES6模块化

node.js 中默认仅支持 CommonJS 模块化规范,如果想基于 node.js 体验与学习 ES6 的模块化语法,需要按照如下两个步骤进行配置

  • 确保安装了 v13.0.0 或更高版本的 node.js
  • 在 package.json 的根节点中添加 "type": "module"节点

image.png 注意: 配置之后,则只能使用ES6模块化语法,不能再使用CommonJS语法了

基本文件结构

image.png

代码内容

image.png

运行

node index.js

es6模块化的内容学习

整体导出

image.png

单个导出

image.png

导入导出使用别名

导出使用别名

image.png 导入使用别名

image.png

整体导入

image.png 注意,直接写import obj from './tool.js'会报错。

默认导出

image.png 此时可以任意使用变量名,即:obj可以改成其他名字。

默认导出和整体导出一起使用

image.png

拓展:让chrome浏览器支持es6模块化

文件目录

- index.html
- index.js
- tool.js

index.html


<!DOCTYPE html>
<html lang="zh">
  <script type="module" src="./index.js"></script> 
</html>

index.js


import {a,b} from './tool.js'
console.log(a,b)

tool.js


export const a = 1;
export const b = 2;

步骤

需要两个步骤,就可以在chrome浏览器感受es6的模块化了

  1. 启用es6的特性.

    打开chrome浏览器,在地址栏中输入 chrome://flags; 找到experimental javascript,启用它;最后重启chrome浏览器。(注,我的版本是:chrome74.0.3729.131)

image.png 2. 修改index.html中引入.js 的方式

image.png 注意到上面的type="module"