注意:最新版本的chrome浏览器已支持module语法,需要在web服务器环境下运行!
设置浏览器启用es6语法功能:
1.在浏览器的url中输入:chrome://flags/
设置下面选项为enable,重启浏览器。
测试代码
mokuai.js
let myName = "Tom"; let myAge = 20; let myfn = function(){ return "My name is" + myName + "! I'm '" + myAge + "years old." } let myClass = class myClass { static a = "yeah!"; } export { myName, myAge, myfn, myClass }
all.js
import { myName, myAge, myfn, myClass } from "./mokuai.js"; console.log(myfn());// My name is Tom! I'm 20 years old. console.log(myAge);// 20 console.log(myName);// Tom console.log(myClass.a );// yeah!
index.html 引入all.js
注意 type="module" 是必须加的告诉浏览器是ES6
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <script type="module" src="/all.js" data-main="/basic/js/jquery"></script> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>测试</title> </head> </html>