Babel์ ECMAScript 2015+ ๋ฌธ๋ฒ์ผ๋ก ์์ฑ๋ ์ฝ๋๋ฅผ ECMAScript 2015+ ๋ฅผ ์ง์ํ์ง ์๋ ๋ธ๋ผ์ฐ์ ์์๋ ๋์ํ๋๋ก ์ฝ๋๋ฅผ ๋ณํํด์ฃผ๋ ํด์ด๋ค. ๊ทธ ๋ฐ์๋, React์ JSX, ํ์ ์คํฌ๋ฆฝํธ์ ๋ฌธ๋ฒ ๋ฑ๋ ๋ณํ ํ ์ ์๋ค.
// Babel Input: ES2015 arrow function
[1, 2, 3].map((n) => n + 1);
// Babel Output: ES5 equivalent
[1, 2, 3].map(function(n) {
return n + 1;
});
babel core๋ ์ฝ๋๋ฅผ ์ปดํ์ผํ ํ ์ถ๋ ฅ(parsing โก printing) ํ๋ ์ญํ ์ ํ๋ฉฐ, babel cli๋ babel์ terminal ํ๊ฒฝ์์ ์คํํ ์ ์๊ฒ ํด์ฃผ๋ ์ญํ ์ ํ๋ค.
//app.js
const code = () => {
console.log("hi")
}
์์ ๊ฐ์ ์ฝ๋๋ฅผ babel cli ๋ช
๋ น์ด๋ฅผ ์ด์ฉํด ์ปดํ์ผ ํด๋ณด๋ฉด ์๋์ ๊ฐ์ ๊ฒฐ๊ณผ๊ฐ ๋์จ๋ค.
babel plugin์ babel core๊ฐ ์ปดํ์ผ ์ค์ธ ์ฝ๋๋ค์ ์ค์ง์ ์ผ๋ก ๋ณํ(parsing โก transform โก printing) ์์ผ์ฃผ๋ ์ญํ ์ ํ๋ฉฐ, ๋ณํ ํ๊ณ ์ ํ๋ ์ฝ๋์ ๋ฐ๋ผ ์ฌ๋ฌ๊ฐ์ง๋ฅผ ์ ์ฉํ ์ ์๋ค.
@babel/plugin-transform-arrow-functions
๊ณผ @babel/plugin-transform-block-scoping
๋ฅผ ๋์์ ์ ์ฉํ ๊ฒฐ๊ณผ์ด๋ค.์ฌ๋ฌ๊ฐ์ ํ๋ฌ๊ทธ์ธ๋ค์ ๋์์ ์ฌ์ฉํ๊ณ ์ ํ ๋, ํ๋ฌ๊ทธ์ธ๋ค์ ๊ฐ๋ณ์ ์ผ๋ก ์ค์นํด ์ ์ฉํ๋ ๊ฒ์ด ์๋, ํ๋ฌ๊ทธ์ธ๋ค์ ํ๋ฒ์ ์ ์ฉํ ์ ์๊ฒ๋ ๋ฌถ์ด๋์ ๊ฒ์ด๋ค.
Presets can act as an array of Babel plugins
๋ํ์ ์ธ ์ข
๋ฅ๋ก๋ @babel/preset-env
, @babel/preset-flow
, @babel/preset-react
, @babel/preset-typescript
๊ฐ ์๋ค.
@babel/plugin-transform-arrow-functions
๊ณผ @babel/plugin-transform-block-scoping
๋ฅผ ์ ์ฉํ์ง ์์์์๋ ํ์ดํ ํจ์์ ๋ณ์๊ฐ ๋ณํ๋ ๊ฒ์ ์ ์ ์๋ค.์ง๊ธ๊น์ง babel์ ์ ์ฉํ๊ธฐ ์ํด์ babel cli ํ๊ฒฝ์์ plugin๋ค๊ณผ preset๋ค์ ์
๋ ฅํด ์ ์ฉํ์๋ค. ํ์ง๋ง plugin, preset๋ค์ ๊ฐฏ์๊ฐ ๋ง์์ง๋ฉด cli ํ๊ฒฝ์ผ๋ก ์ ์ฉํ๋๋ฐ ํ๊ณ๊ฐ ์๋ค.
์ด๋ฌํ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด babel config file์ ์ด์ฉํ๋ค. babel config file์ babel๊ณผ ๊ด๋ จ๋ ์ค์ ์ฌํญ๋ค์ ์
๋ ฅํ ํ babel์ ์คํํ๊ฒ ๋๋ฉด, babel์ด config file ์๋์ผ๋ก ์ฐพ์ ํ file์ ์ค์ ๋๋๋ก ์ฝ๋๋ฅผ ๋ณํํ๋ค.
babel config file๋ช ์
babel.config.json
,babel.config.js
.babelrc.json
๋ฑ ๋ค์ํ๋ค. (https://babeljs.io/docs/en/config-files ์ฐธ๊ณ )
// babel.config.json
{
plugins: [
"@babel/plugin-transform-arrow-functions",
// @babel/transform-arrow-function๊ณผ ๋์ผ
"@babel/plugin-transform-block-scoping"
// @babel/transform-block-scoping๊ณผ ๋์ผ
]
}
์์ ๊ฐ์ด config file์ ์ค์ ํ ํ babel์ ์คํํ๋ฉด, cli ํ๊ฒฝ์์ --plugins ์ต์
์ผ๋ก ํ๋ฌ๊ทธ์ธ์ ์
๋ ฅํ์๋์ ๋์ผํ ๊ฒฐ๊ณผ๋ฅผ ์ป์ ์ ์๋ค.
๋ค์๊ณผ ๊ฐ์ด ํ๋ฌ๊ทธ์ธ ๋ณ๋ก ์ต์ ๋ค์ ์ง์ ํด ์ค ์๋ ์๋ค.
// babel.config.json
{
plugins: [
["@babel/plugin-transform-arrow-functions", {options}],
// @babel/transform-arrow-function๊ณผ ๋์ผ
"@babel/plugin-transform-block-scoping"
// @babel/transform-block-scoping๊ณผ ๋์ผ
]
}
// babel.config.json
{
plugins: [
"@babel/transform-arrow-functions",
"@babel/transform-block-scoping"
],
presets: [
"@babel/preset-env"
]
}
์์ ๊ฐ์ด config file์ preset๋ค์ ์ค์ ํด์ฃผ๋ฉด, cliํ๊ฒฝ์์ --presets์ต์
์ผ๋ก preset๋ค์ ์
๋ ฅํ๋ ๊ฒ๊ณผ ๊ฐ์ ๊ฒฐ๊ณผ๋ฅผ ์ป์ ์ ์๋ค.
ํ๋ฌ๊ทธ์ธ๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก preset๋ํ ์ต์ ์ ์ค์ ํด ์ค ์ ์๋ค.
// babel.config.json
{
plugins: [
"@babel/transform-arrow-functions",
"@babel/transform-block-scoping"
],
presets: [
["@babel/preset-env", {
"targets": {
"chrome": "58",
"ie": "11"
// ์ง์ํ๊ณ ์ํ๋ ๋ธ๋ผ์ฐ์ ๋ฒ์
}
}]
]
}