如何使用es6模塊化?
使用起來其實非常簡單
在 module1.js 中
var hello = 'hello world !';
function sayHello(){
console.log('hello dear !')
}
export {hello,sayHello} //對外暴露
在 main.js 中
// 在引入的時候使用es6的對象的解構賦值
import {hello,sayHello} from './module1.js'
console.log(hello); // hello world !
sayHello(); // hello dear !
在 index.html 中
<script type="text/javascript" src="js/src/main.js"></script>
創建一個.babelrc文件(注意前綴有個.)
{
"presets":["es2015"]
}
此時打開 index.html 時,在控制臺中可見報錯
Uncaught SyntaxError: Unexpected token import
因為瀏覽器無法識別 import 和 export 語法,所以要對js進行編譯
在根目錄下,使用一下命令安裝 babel 和 browserify
$ npm install babel-cli browserify -g
$ npm install babel-preset-es2015 --save-dev
安裝完成之后,使用babel將es6編譯為es5代碼(但包含CommonJS語法)
$ babel js/src -d js/lib
// -d 左側是 main.js 和 hello.js 的位置
// -d 右側是 bable編譯后,會自動新建一個文件夾作為 編譯后js 文件存放的位置
使用 browserify 編譯js
browserify js/lib/main/js -o js/dist/bundle.js
// 使用 browserify 編譯時,不會自動創建編譯后的文件夾,需要事先手動創建
// -o 左側是 需要編譯的js文件的位置
// -o 右側是 編譯之后的js存放的位置
編譯完成之后,修改 index.html 引入的 main.js 文件的位置
<script type="text/javascript" src="js/src/main.js"></script>
修改為--->
<script type="text/javascript" src="js/dist/bundle.js"></script>
此時打開 index.html ,打開F12即可看到
hello world !
hello dear !