> 文档中心 > JS模块化

JS模块化

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)中引用

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

注意点:

1.type = "module" 必须标识

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

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

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

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

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