ES6代码暴露的三种方式

JS模块化主要有 CommenJS(node)、JS module(es6)。

一、Commen JS

Commen JS主要是node环境中用于模块化开发,每一个js文件都是一个模块,有自己的作用域,其中的变量和函数都是私有的,对外部js文件不可见。

使用module.exports或exports关键字进行对外暴露,*可以在普通的js文件中使用*

1.text.js中的模块 module.exports写法(以下三中写法完全一样)

function a(){
  console.log('a');
}
function b(){
  console.log('b');
}
module.exports = {a,b}
module.exports = {
  a(){
    console.log('a');
  },
  b(){
    console.log('b');
  }
}
module.exports.a = function(){
  console.log('a');
}
 
module.exports.b = function(){
  console.log('b');
}

在index.js中使用require引用

const qwe = require('./text')
qwe.a()  // 'a'
qwe.b()  // 'b'

2.当使用module.exports暴露一个数据时,引用有所不同

// text.js中对外暴露的模块
module.exports = function(){
  console.log(123);
}
 
 
// index.js中引用
const qwe = require('./text')
qwe() // 注意此处直接调用即可

3.text.js中的模块 exports写法(只有一种写法)

exports.a = function(){
  console.log('a');
}
 
exports.b = function(){
  console.log('b');
}

在index.js中使用require引用

const qwe = require('./text')
qwe.a()  // 'a'
qwe.b()  // 'b'

二、JS module

JS module是es6中的语法,用来模块化的开发。使用export、import语法,有三种对外暴露方式:分别暴露、统一暴露、默认暴露。

JS module并不能在普通的js文件中使用

*exportimport关键字仅可在模块系统(如vue项目中)中使用----所以不能在普通的js脚本中使用*

1.分别暴露

test.js中的模块

export function a(){
  console.log('a');
}
export function b(){
  console.log('b');
}

index.js中引入

import {a,b} from './text.js'
a() // 'a'
b() // 'b'

2.统一暴露

test.js中的模块

function a(){
  console.log('a');
}

function b(){
  console.log('b');
}

export {a,b}

index.js中引入

import {a,b} from './text.js'
a() // 'a'
b() // 'b'

3.默认暴露

test.js中的模块

export default {
  a(){
    console.log('a');
  },
  b(){
    console.log('b');
  }
}

index.js中引入

import qwe from './text.js'
qwe.a() // 'a'
qwe.b() // 'b'

三、在HTML页面中使用JS module

在HTML页面中不能使用Commen JS,Commen JS用于node模块系统。

在HTML页面可以使用JS module,但是需要一些配置。

如test.js中的模块

export default {
  a(){
    console.log('a');
  },
  b(){
    console.log('b');
  }
}

在HTML(index.html)中引用

<script type="module">
    import qwe from './text.js'
 
    qwe.a() // 'a'
    qwe.b() // 'b'
</script>

注意点:

1.type = "module" 必须标识

2.引用路径必须使用相对路径

3.文件名不能省略 .js 后缀

4.必须使用 Live Server 插件运行(vs中安装即可)

如果不开启 Live Server 运行,而是直接双击HTML文件打开,会因为浏览器的安全机制不允许在本地运行,会当作跨域访问报错。

img

img

开启 Live Server,以域名的形式进行访问:

img

img

posted @   哩个啷个波  阅读(498)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示