关于ES6模块公开与导入

假设tools.js是工具模块
假设app.js是入口。

如果在tool.js中使用下列公出:

1
2
3
4
5
6
7
8
9
export const a = {
}
export const b = {
    b'b'
}
export const c = (e) =>{
    console.log( e )
    return true;
}

即公出多个对象,
app.js中正确导入如下:

1
import {a,b,c} from '../../utils/tools'

取值如下:

1
2
3
a;
b;
c()

同理,如果在tool.js中使用下列公出:

1
2
3
4
5
6
7
8
9
10
11
12
 const a = {
}
 const b = {
    b'b'
}
 const c = (e) =>{
    console.log( e )
    return true;
}
export default {
    a , b , c
}

即公出单个对象,对象内含多个元素,
则app.js中正确导入如下:

1
import onlyOneParam from '../../utils/tools'

取值如下:

1
2
3
onlyOneParam.a
onlyOneParam.b
onlyOneParam.c()

End。
如果两种同时使用:取法不冲突能同时兼容。但是export default只能在一个模块中只能有一个,export可以有多个。
以上情况实测环境是vue项目中,如果是node开发肯定是不支持这类写法的,nodejs 本身是有自己的模块系统方式的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// tools.js
let sex = "boy";
module.exports = {
    sex
}
&
let sex = "boy";
module.exports = sex
app.js
const {sex} =  require('./tools');
console.log( sex ) 
&
const any =  require('./tools');
console.log( any.sex );

不管用哪种公开方法,

1
import * as onlyOneParam from '../../utils/tool'

这个取法都能取到值,层级不同而已。