import和export
首先这两个是基于服务器端环境的 我这边是安装了phpstudy 安装好之后会有一个www文件夹 把内容放入该文件夹中我的文件夹叫exportandimport 里面有一个index.js 和一个index.html 可以启动服务器 http://localhost/exportandimport/index.html
下面的export写在index.js文件中,import写在index.html中,注意:在index.html中引入js文件时,要
写成如下形式:
<script type="module">
</script>
下面介绍第一种情况
//inde.js文件
//1.第一种情况
export let a='张三';
//index.html文件
<script type="module">
import {a} from "./index.js"//""内是js文件路径
console.log(a);
</script>
第二种情况
//inde.js文件
//1.第二种情况
export function fn(){
console.log('我是函数fn')
}
//index.html文件
<script type="module">
import {fn} from "./index.js"//""内是js文件路径
fn();
</script>
第三种情况
//inde.js文件
//1.第三种情况
let a=1;
let b='zhangsan';
let c='3';
function d(){
console.log('我是函数d')
}
export {a,b,c,d};
//index.html文件
<script type="module">
import {a,b,c,d} from "./index.js"//""内是js文件路径
console.log(a,b,c);
d();
</script>
第四种情况
//inde.js文件
//1.第四种情况:如果想隐藏js文件中的变量名,可以在导出时给变量名用as起个别名
let a=1;
let b='zhangsan';
let c='3';
export {a as mya,b as myb,c as myc,d};
//index.html文件
<script type="module">
//导入时也要用相对应的别名
import {mya,myb,myc} from "./index.js"//""内是js文件路径
console.log(mya,myb,myc);
d();
</script>
第五种情况
//inde.js文件
//1.第五种情况
let a = 1;
export default a;
//index.html文件
<script type="module">
import aaa from "./index.js"//export default导出时,import中可以给任意名
console.log(aaa);
</script>
第六种情况
//inde.js文件
//1.第六种情况
export default {
b: 1,
a() {
console.log('a');
}
};
//index.html文件
<script type="module">
import aaa from './index.js';
aaa.a();
console.log(aaa.b);
</script>
第七种情况
//inde.js文件
//1.第三种情况
let a=1;
let b='zhangsan';
let c='3';
function d(){
console.log('我是函数d')
}
export {a,b,c,d};
//index.html文件
<script type="module">
import * as aaa from "./index.js"//""内是js文件路径
console.log(aaa.a,aaa.b,aaa.c);
aaa.d();
</script>