认知一: 导出的对象被修改,依然会影响原来的对象。
仔细想想这是理所当然的事(说明导出的依然是对象指向内存的地址,所以通常还需要结合深拷贝使用)
/**
export const state = {
select: 0
}
export const logstate = () => {
console.log('what the fuck?', state)
}
*/
import { state, logstate } from './lib'
state.select = 110
console.log('fuckyou', state) // fuckyou { select: 110 }
logstate() // what the fuck? { select: 110 }
认知二:无论是 let 还是 const ,导出的变量都无法修改
/**
export let val = 0
*/
import { val } from './lib'
val = 110 // 报错: "val" is read-only
认知三: import 无法解构 export default {...} 导出的对象,哪怕他真的是导出一个对象!
我们知道,如果我们用常规的 require 导入 export default {...},其实还有一层 default 的:
/**
const state = {
select: 0
}
const logstate = () => {
console.log('what the fuck?', state)
}
export default {
state,
logstate
}
*/
const what = require('./lib');
console.log(what); // { default: { state: { select: 0 }, logstate: [Function: logstate] } }
而神奇的是,如果使用 Import 就会自动将这一层多余的default移出:
import what from './lib'
console.log(20190111214203, what) // { state: { select: 110 }, logstate: [Function: logstate] }
但尽管如此,我们依然无法使用解构:
import what from './lib'
import { state, logstate } from './lib'
console.log(state, logstate) // undefined undefined
如果实在想使用解构,只能用最初的require方法了,但要记得加上 .default 哦:
const { state, logstate } = require('./lib').default
console.log(state, logstate) // { select: 0 } [Function: logstate]