es6中的import,export浏览器已经支持

直接上代码, 成功测验了es6的新特性 import , export语法。

服务器返回 js文件时,要加上content-type: applicaiton/javascript 这个字段。

index.html

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, minimum-scale=1.0">
<script type="module">
    import { foo,name,s } from './foo.js';

    alert(foo());
    alert(name);
</script>

foo.js

export function foo() {
  return 'bar';
}
export var name='ljl';

//另外,export支持别名导出, 所以改成下面这样也是可以的。

export function foo() {
  return 'bar';
}
 var name='ljl';
var age = 28;
export{age,name as nale, name}

  

chrome 浏览器version 68 :运行(http://localhost:8080/index.html)结果如下

去掉我故意加入的 "s"后, 就不会报错了。

另外,当然抽成3个文件也是可以的。

也能运行成功。

参考原文:https://jakearchibald.com/2017/es-modules-in-browsers/

https://segmentfault.com/a/1190000014342718

----------------------------------------------------------------------------------------------------------------------

https://www.sitepoint.com/understanding-es6-modules/

原文地址:https://www.cnblogs.com/oxspirt/p/9732236.html