js匯入匯出
CommonJS
commonJS是Node服務器模塊規范,每個檔案就是一個模塊,有自己的作用域,每個模塊里面的東西都是私有的,其他模塊不能呼叫,CommonJS規定,每個模塊內部:module代表當前模塊,這個變數是一個物件,module物件下有個屬性exports也是一個物件,exports就是模塊的對外介面,想匯出某個方法,變數等就把它放到exports下,用require匯入即可,
// 1.js
var a = 1;
function b(){
console.log(2)
}
module.exports = {
a,b
}
// 匯出了變數a與方法b
// 2.js
var a = require('./1') // 這里的變數a就相當于 1.js里的module.exports
console.log(a.a) // 1
a.b() // 2
也可以直接使用exports匯出,只能一個一個匯出
// 1.js
var a = 1;
function b(){
console.log(2)
}
exports.a = a;
exports.b = b;
// module.exports = { a }
// 注意:exports 不能和 module.exports混用,兩個都存在的時候只有module.exports生效
在node中是不可以使用es6的匯入匯出語法的,如果需要使用es6的匯入匯出請安裝必要的插件
// 安裝必要的插件
npm install babel-cli -g
npm install babel-preset-env -D
// 運行你寫es6的模塊時 把 node index.js 改成 babel-node --presets env index.js這樣就可以成功運行了,
es6
es6在語言標準層面上實作了模塊的匯入匯出功能,es6 使用export與export default匯出模塊,使用import匯入模塊,也可以使用require匯入模塊,但是不建議
// 1.js
var a = 1;
function b (){
console.log(module)
console.log(2)
}
export { // 匯出了變數a和方法b
a,b
}
// 2.js
import {a,b} from './1' // 使用export 匯出時 匯入必須為 {},{}內是想匯入的東西
console.log(a) // 1
b() // 2
// ------------------------------------------------
// export 可以按需引入 export default 不行
// 2.js
import {a} from './1' // 這樣就只引入了變數a
// 1.js
var a = 1;
function b (){
console.log(module)
console.log(2)
}
export { a }
export { b }
// export 能匯出多次 export default 不行
// 1.js
var a = 1;
function b (){
console.log(2)
}
export default {a,b} // export default在模塊內只能出現1次
// 2.js
import s from './1' // 匯出為export default時,匯入用一個變數接收
console.log(s.a) // 1
s.b() // 2
// 1.js
var a = 1;
function b (){
console.log(2)
}
const c = 3;
export default { a,b }
export { c } // 兩個可以同時存在,匯入的方式也分為兩個
// 2.js
import s from './1'
import {c} from './1'
console.log(s.a) // 1
s.b() // 2
console.log(c) // 3
注意事項
在專案中,比如說vue
import {b} from "./2"
module.exports = {
b
}
// 用es6匯入,comm匯出 會報錯
var a = require('./1')
export {
a
}
// 用comm匯入,es6匯出 可以正常執行
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/281319.html
標籤:區塊鏈
上一篇:JAVA基礎匯總:第一章
下一篇:區塊鏈初識
