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导出 可以正常执行