ES6模块化改变前端的原生开发方式
文章目录
ES6推出的模块化,使用方式有点类似 require.js,只需要引入一个入口文件即可,其他的js文件可以按功能创建及引入,export 导出方法属性,然后 import 引入使用,这个新特性可能在未来会引来原生开发的热潮,不需要三方框架(vue、react)即可自由使用模块化开发,而且目前浏览器市场快统一了,就连IE也放弃了自己的内核使用google webkit内核了,而且电脑也是默认配备了 IEAdge浏览器,想想就觉得爽。
PS:使用模块化加载,需要服务器环境,也就是得通过localhost访问,而且script标签也得加上type="module"声明
一、基本示例
a.js
export default function a1() {
console.log('a1')
}index.html
<script type="module">
import a1 from './a.js'
a1() // a1
</script>二、解构赋值
c.js
export function c1() {
console.log('c1')
}
export function c2() {
console.log('c2')
}index.html
<script type="module">
import { c1, c2 } from './c.js'
c1() // c1
c2() // c2
</script>三、js文件引入
a.js
export default function a1() {
console.log('a1')
}b.js
import a1 from './a.js'
export default function b1() {
a1()
console.log('b1')
}index.html
<script type="module">
import b1 from './b.js'
b1() // a1, b1
</script>四、标签引入
d.js
import a1 from './a.js'
a1()
console.log('d1')index.html
<script type="module" src="./d.js"></script>综合上述几种情况,是不是感觉同 vue 或 react 开发使用方式一样,只不过这里需要通过 script 模块类型声明,但要知道这是原生的啊,不用搭建一套脚手架即可直接使用,如果是做一些系统项目话可以考虑直接“上马”。
更多前端知识,请关注小程序,不定期有惊喜!

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论