動態

詳情 返回 返回

js模塊化 - 動態 詳情

js模塊化

https://blog.csdn.net/weixin_...

https://zh.javascript.info/mo...

commonJS

基於node端的運行

暴露
const name = "xxx";
const age = 1;

/**
 * moudle.exports={}暴露
 */
module.exports = {
    getName,
    getAge,
    name,
    age
};

function getName() {
  return this.name;
}

function getAge() {
    return this.age;
}
/** 
 * 使用exports.xxx=value暴露
 */

exports.add= function(a,b){
    return a + b;
}
引入
/**
 * 暴露的本質是以module.exports為主
 * module.exports和exports不能混用,不然以module.exports為主
 */
const xiaomao = require("./m1");//引入自定義模塊
const m3=require("./m3");//引入自定義模塊
const uniq=require('uniq');//引入第三方模塊
xiaomao.getName();
xiaomao.getAge()
m3.add(1,11)

let arr=[1,1,3,4,423,-1,-100,323,22,11,1,33,4,2,111,32321]
uniq
//數組去重和排序(字典排序)
uniq(arr)

基於瀏覽器端的運行

image-20220717143608477

全局安裝browserify npm browserify -g

對app.js進行編譯,生成buid.js

browserify ./app.js -o ./buid.js

在頁面引入buid.js

es6

編譯

babel用於編譯es6為es5,browserify用於編譯node.js為瀏覽器識別的js

全局安裝:babel-cli、Browserify :npm install babel-cli browserify -g

   局部安裝:babel-preset-es2015: `npm install babel-preset-es2015`


以上是否需要編譯待定

在node中可以直接使用,在頁面直接加上type=''module“也可以直接使用

https://www.ruanyifeng.com/bl...

有待商榷

分別暴露

export const data='asheh'
export const msg='ssss'
export function showMsg(){
    console.log(msg);
}
export function showData() {
    console.log(');
}

統一暴露

const school='尚硅谷'
const person={
    name:'老劉',
    age:18,
    sex:'女'
}
function getLaoliu(){
    console.log(person)
}
//統一暴露--常用`在這裏插入代碼片`
export {school,person,getLaoliu}
//支持改名
export {school as school ,person as person,getLaoliu as getLaoliu}

默認暴露 (適合只暴露一個數據) 只能暴露一次

export default {
    name:"wc",
    age:5
}

混合使用

# [分別暴露]
export const teacher1={name:'強哥',age:15}
export const teacher2={name:'ke 哥',age:35}
# [統一暴露]
const stu1= {name:'網哥',age:25}
const stu1= {name:'掌聲',age:33}
export {stu1,stu2}

# [默認暴露]
export default{
    school:'上海dax',
    address:'shanghai',
    subject:['計算機','java','大數據']
}

引入方法

# 引入【分別暴露】模塊
import {data,msg,showData,showMsg} form './module1' # 注意不是解構賦值

# 引入【分別暴露】模塊 + 打包加入
import * form './module1'

# 引入【分別暴露】模塊 + 重命名
import {data as data2} form './module2'

# 引入【統一暴露】模塊 (和上面三種一樣)
import {school as sc,person,getLaoliu} form './module3'

# 引入【默認暴露】模塊 
import module4 form './module4'

# 引入多種暴露方式
import module5,{teacher1,teacher2,stu1,stu2} from './module5'

Add a new 評論

Some HTML is okay.