likes
comments
collection
share

js模块化

作者站长头像
站长
· 阅读数 377

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)

基于浏览器端的运行

全局安装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'
转载自:https://segmentfault.com/a/1190000042252648
评论
请登录