ES6 시작하기. 개발 환경 세팅.
ES6는 자바스크립트의 새로운 버전이다. 오래된 새로움이지만...
우리가 ES6를 써야하는 이유는 '편하다'이다.
공부를 하고 나면 새로운 JS가 편하고 강력하게 느껴지길 바란다.
ES6를 제대로 써보려면 두가지 작업 환경을 세팅해야 한다.
- Babel : ES6 코드를 ES5 코드로 바꿔준다.
- Webpack : 의존 관계에 있는 여러 스크립트 파일들을 하나의 파일로 묶어준다. (이미지와 css까지도!!)
10분이면 끝나니 같이 해보자. 먼저 Babel부터.
먼저 폴더를 하나 만들고
1. package.json 파일을 만들자.
npm init -y
- 바벨 설치
npm install --save-dev @babel/core @babel/cli
2. 바벨 프리셋 설치 - 기본 바벨 환경 설치.
npm install --save-dev @babel/preset-env
3. 루트에 .babelrc 파일을 생성하고 프리셋 사용 설정 입력
{ "presets": ["@babel/preset-env"] }
4. package.json 파일에 바벨 명령어를 스크립트로 지정해놓자.
"scripts": {
"build": "babel src/js -w -d dist/js"
}
src/js 폴더의 파일들을 변환 후 dist/js에 저장하겠다는 의미다.
이제 src/js 폴더에 ES6 스크립트 파일을 생성하고 npm run build 를 입력하면 dist/js에 ES5로 변환된 스크립트들이 저장된다.
바벨 설치는 끝났다.
이제 Webpack을 설치해보자.
1. Webpack 설치
npm install --save-dev webpack webpack-cli
2. babel loader 설치 - Webpack이 파일을 합칠때 ES6 -> ES5로 변환하도록 한다.
npm install --save-dev babel-loader
3. package.json 파일에 바벨 명령 스크립트를 Webpack 명령으로 바꿔주자.
"scripts": {
"build": "webpack -w"
},
4. 루트에 webpack.config.js 파일을 만들자. Webpack이 실행될 때 참조하는 설정 파일이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
const path = require('path');
module.exports = {
entry: './src/js/entry.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'webpack.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, 'src/js')
],
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
},
devtool: 'source-map',
// https://webpack.js.org/concepts/mode/#mode-development
mode: 'development'
};
|
cs |
이제 src/js/entry.js 를 시작으로 여러 파일들을 자유롭게 만들자.
그리고 npm run build 를 입력하면 dist/webpack.bundle.js 파일 하나로 합쳐준다.
다소 길었지만 ES6 개발 환경이 구축되었다.
아래는 추가 설명이다.
ES6에는 ES5로는 대체할 수 없는 기능들이 있다. 그러한 기능들을 지원하기 위해서는 babel-polyfil을 추가적으로 사용하여야 한다.
1. 설치.
npm install @babel/polyfill
2. webpack.config.js 파일 수정
entry: {
entry: ['@babel/polyfill', './src/js/entry.js']
}
이제 CSS를 JS에 포함시켜보자. 스크립트로 CSS를 생성하고 관리하지 않아도 된다. 세상이 좋아졌음을 느끼게 된다.
1. 설치. node-sass가 sass 컴파일러고 나머지는 Webpack 로더다.
npm install node-sass style-loader css-loader sass-loader --save-dev
2. webpack.config.js 파일 수정.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
const path = require('path');
module.exports = {
entry: ['@babel/polyfill', './src/js/entry.js', './src/sass/main.scss'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'webpack.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, 'src/js')
],
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
],
exclude: /node_modules/
}
]
},
devtool: 'source-map',
// https://webpack.js.org/concepts/mode/#mode-development
mode: 'development'
};
|
cs |
CSS가 몇 만 줄이 넘어가도록 방대해진 경우라면 JS에 포함시키지 않고 따로 CSS파일로 분리해 낼 수도 있다.
1. 설치
npm install --save-dev mini-css-extract-plugin
2. webpack.config.js 파일 수정.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: ['@babel/polyfill', './src/js/entry.js', './src/sass/main.scss'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/webpack.bundle.js'
},
plugins: [
new MiniCssExtractPlugin({ filename: 'css/style.css' })
],
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, 'src/js')
],
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
},
exclude: /node_modules/
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader?outputStyle=expanded'
],
exclude: /node_modules/
}
]
},
devtool: 'source-map',
mode: 'development'
};
|
cs |
CSS파일이 분리 되는 것을 확인 할 수 있다.
마지막으로 JS조차 방대해진 경우 필요한 시점에서만 JS를 로딩하도록 여러 파일로 분리해보자.
pageOne과 pageTwo 라는 멀티엔트리가 적용되고 해당 파일들은 dist/js/pageOne.js 와 dist/js/pageTwo.js로 저장될 것이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
pageOne: ['@babel/polyfill', './src/js/entry.js', './src/sass/main.scss'],
pageTwo : ['./src/js/entry2.js',]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].js'
},
plugins: [
new MiniCssExtractPlugin({ filename: 'css/style.css' })
],
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, 'src/js')
],
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
},
exclude: /node_modules/
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader?outputStyle=expanded'
],
exclude: /node_modules/
}
]
},
devtool: 'source-map',
mode: 'development'
};
|
cs |
참고:
webpack
webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.
webpack.js.org