js模块化语法

70 阅读1分钟

模块化

            => 每个js文件都可以看作一个模块 xx.js
            => 每个js模块中的内容与其它模块相互独立

a暴露模块

法一

    //直接在需要暴露的方法前加export
    export const getMax = function(m,n){
    let max = m
    if(n > max){
        max = n
    }
    return max
}

法二

let sum = getSum()
console.log('sum ',sum)
export {getMax,num}

b引入模块

 import {变量,方法} from './a.js'

index.html用于启动暴露与引入的模块

type="module"必须加上才能启动模块化

index.html
                        <script type="module">
                            import {变量,方法} from './a.js'
                        </script>

默认暴露

    export default {
    name:'jack',
    age:18
}

两种暴露方式的引入的区别

<script type="module">
		import { getMax } from './a.js' // 引入a.js模块中的getMax方法,一般暴露的引入方式
		import jackObj from './c.js'//默认暴露的引入方式
		let max = getMax(20, 34)
			// 显示最大值
			const spanEle = document.querySelector('span')
			spanEle.innerHTML = max 
            console.log('jackObj ',jackObj)
</script>

相互暴露

a可以引入b暴露的内容,反之
a.js
import { getSum } from './b.js'
let num = 100

//直接在需要暴露的方法前加export
export const getMax = function(m,n){
    let max = m
    if(n > max){
        max = n
    }
    return max
}

let sum = getSum()
console.log('sum ',sum)

// export {getMax,num}

b.js
export const getSum = function(){
    let arr = [10,20,30]
    return arr.reduce((privous,current)=>privous = privous + current,0)
}