从一个小栗子说说export,export default

我查到Chrome浏览器已经原生支持es6的模块了,但是要这样用 <script type=module src= ></script> 。还要开一个本地服务器(补充我的是http-server, 安装npm install -g http-server  简单用法 http-server -p 3001,开启一个3001端口的本地服务器),不用用file:///es6test.html

//es6test.html

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8><meta name=viewport id=viewport content="target-densitydpi=1,width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1"><title>vue_1018</title>
<link href=static/css/app.d41d8cd98f00b204e9800998ecf8427e.css rel=stylesheet>
</head>
<body>
<div id=app>es6</div>
<script type="module" src="static/js/es6.js"></script>
<script type="module">
import {str,log} from './static/js/es6.js'; //也可以分开写两次,导入的时候带花括号
console.log(log(str));
</script>
</body>
</html>

//es6test.js

export const str = "blablabla~";
export function log(sth) { 
  return sth;
}

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

//es6test.html

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8><meta name=viewport id=viewport content="target-densitydpi=1,width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1"><title>vue_1018</title>
<link href=static/css/app.d41d8cd98f00b204e9800998ecf8427e.css rel=stylesheet>
</head>
<body>
<div id=app>es6</div>
<script type="module" src="static/js/es6.js"></script>
<script type="module">
 import {str} from './static/js/es6.js'; //也可以分开写两次,导入的时候带花括号
 console.log(str);
</script>
</body>
</html>

//es6test.js

export const str = "blablabla~";
export function log(sth) { 
  return sth;
}

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

上面都是正确的写法

常见错误,1、import str from './static/js/es6.js';   //报Uncaught SyntaxError: The requested module does not provide an export named 'default'

2、import str from './static/js/es6.js'; 

 //es6test.js

export default const str = "blablabla~";
export function log(sth) { 
  return sth;
}

//报Uncaught SyntaxError: Unexpected token const

这样写就可以了:

  import {str} from './static/js/es6.js'; 
  console.log(str);

  //es6test.js

 const str = "blablabla~";
 export default str;
export function log(sth) { 
  return sth;
}   //blablabla~




©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页