如何用babel來編譯ES6的代碼

1.安裝基本的依賴

npm i babel-cli babel-core babel-preset-es2015 babel-preset-stage-0

2.創(chuàng)建.babelrc來定義編碼規(guī)范

{
  "presets": ["es2015", "stage-0"]
}

3.用ES6編寫一個(gè)helloWorld.js,并且編寫一個(gè)index.js來調(diào)用這個(gè)helloWorld.js

helloWorld.js

export default function Test(){
    console.log(123)
}

index.js

import index from './index.js'
console.log(index)

4.使用babel來進(jìn)行轉(zhuǎn)碼

babel index.js --out-dir ./build

5.生成的代碼

'use strict';
var _index = require('./index.js');
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_index2.default);

6.結(jié)論

從生成的代碼來看,里面還有require之類的,可以在node環(huán)境中執(zhí)行看看效果,但是在執(zhí)行的時(shí)候,helloWorld的代碼并沒有轉(zhuǎn)換,直接報(bào)錯(cuò)了,所以,這只是用來轉(zhuǎn)換單個(gè)文件使用的,建議還是采用webpack來進(jìn)行轉(zhuǎn)碼,直接可以用在html中
注:有興趣的同志可以試試轉(zhuǎn)化以下代碼

let arr=[1,2,3]
arr.map((ele)=>{
    console.log(ele)
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容