在node环境下require一个包时,发现需要这么引入:const axios = require('axios').default
有点疑惑,const axios = require('axios')
的axios是被包裹在default这个属性里面的。
而换成import,import axios from 'axios'
这样写就可以。
为什么呢?
其实很简单,axios这个模块是一个es6模块,是用ESModule的标准写的。它里面是这样导出的:export default xxx
,相当于export {xxx as default}
。对外把变量命名为了default。
于是我们可以通过import {default as axios} from './axios'
,简写为import axios from 'axios'
。即,我们自己把default再命名为axios。
default语法糖有很多好处,我们在使用很多包的时候,开箱即用,反正他们都叫default,不必再费心去想作者给他们取了什么名字了。
而require在commonJS中对应module.exports的部分。当require去处理ES6的导出时,对它而言,ES6的代码就会被转化成这样:
module.exports = {
"default": xxx
}
于是,在ES6语法糖default的影响下,require导出的不是xxx这个对象,xxx是作为default的值,被包在一个更大的对象里。
Finally, the require and require.default… when dealing with ES6 imports (export default MyComponent), the exported module is of the format {“default” : MyComponent}. The
import
statement correctly handles this assignment for you, however, you have to do therequire("./mycomponent").default
conversion yourself. The HMR interface code cannot useimport
as it doesn’t work inline. If you want to avoid that, usemodule.exports
instead ofexport default
.