Webpack-v2 Module Plugin

Webpack2 Loader Module

webpack의 로더 모듈을 사용할려면 webpack이 기본적으로 설치 되어 있어야 한다.
기본 설치 및 사용법은 webpack 내용 참조
webpack 모듈 로더의 경우 작성 문법이 기존과 다르게 변경이 되었다. 여기서는 현재 최신 버전인 webpack2 문법 기준으로 정리한다.

babel 로더

webpack 은 babel을 이용하여 EcmaScript2015(ES6) 문법으로 코드 작성이 가능하다.

1
$ npm i -D babel-core babel-preset-latest babel-loader
  • babel-core: requireJS 문법을 이용해도 모듈 번들링을 할 수 있지만, ES6의 import, export를 사용해보기 위해 babel을 사용
  • babel-preset-latest: babel에는 plugin이라는 게 존재한다. 이 plugin은 es6의 애로우 펑션을 지원하는 플러그인, 클래스를 지원하는 플러그인 등등이 있다. 그러한 플러그인을 모아놓은 걸 preset이라고 부른다. es2015 preset은 es6의 플러그인들을 모아놓은 것이고, latest preset은 ES2015~ES2017까지의 프리셋들을 모아놓은 것이다. 시간이 지나면 latest의 지원 프리셋 범위는 더 늘어날 수도 있다.
  • babel-loader: 웹팩과 바벨을 연동해서 사용하기 위한 로더.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // webpack.config.js

    module.exports = {
    module: {
    rules: [{
    test: /\.js$/,
    // exclude: /(node_modules|bower_components)/,
    use: [
    {loader: 'babel-loader', options: {
    presets: [
    // ['es2015', {moduels: false}]
    ['latest', {moduels: false}]
    ]
    }}
    ]
    }]
    }
    };

CSS 로더

webpack 은 javascript 모듈뿐만 아니라 css, sass, less도 지원한다.

1
$ npm i -D style-loader css-loader node-sass sass-loader postcss-loader autoprefixer
  • style-loader css-loader: css 모듈을 import 시키기 위한 로더
  • node-sass sass-loader: scss 모듈을 import 시키기 위한 로더
  • postcss-loader autoprefixer: (s)css 파일 등등에 벤더 프리픽스를 자동으로 붙이는 로더
    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
    // webpack.config.js

    module.exports = {
    module: {
    rules: [{
    test: /\.css$/,
    // exclude: /node_modules/,
    use: [
    'style-loader',
    {loader: 'css-loader', options: {sourceMap: true}},
    {loader: 'postcss-loader', options: {
    plugins: (loader) => [
    autoprefixer({
    browsers: ['last 2 version', 'ie >= 10']
    })
    ]
    }}
    ]
    }, {
    test: /\.(scss|sass)$/,
    // exclude: /node_modules/,
    use: [
    'style-loader',
    {loader: 'css-loader', options: {sourceMap: true}},
    {loader: 'postcss-loader', options: {
    plugins: (loader) => [
    autoprefixer({
    browsers: ['last 2 version', 'ie >= 10']
    })
    ]
    }},
    {loader: 'sass-loader', options: {sourceMap: true}}
    ]
    }]
    }
    };

file 로더, url 로더

webpack은 css 파일이나 이미지 파일 및 폰트도 하나의 모듈로 인지하기 때문에, 기본적으로 html 파일에서 <img src=”image.png”> 요소를 사용하려면, js 파일에서 require(./image.png) 를 따로 선언해주어야 한다.
부트스트랩, 폰트어썸, 제이쿼리, 이미지 모듈을 사용하기 위해서는 url-loaderfile-loader 로더를 사용해야 한다.

1
$ npm i -D url-loader file-loader
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
// webpack.config.js

module.exports = {
module: {
rules: [{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{loader: 'url-loader', options: {
limit: 10000,
mimetype: 'application/font-woff',
name: 'fonts/[name].[ext]'
}}
]
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{loader: 'file-loader', options: {
name: 'fonts/[name].[ext]'
}}
]
}, {
test: /\.(jp(e)g|gif|png)?$/,
use: [
{loader: 'file-loader', options: {
name: 'img/[name].[ext]'
}}
]
}]
}
};

webpack2 Plugin

webpack의 플러그인은 js 난독화 플러그인, 번들 파일을 html에 자동으로 삽입해주는 플러그인 등 기본적으로 제공하는 플러그인 외 다양한 종류가 많다.

1
$ npm i -D html-webpack-plugin clean-webpack-plugin extract-text-webpack-plugin
  • html-webpack-plugin: html에 번들링 된 bundle.js 파일을 자동으로 삽입하는 플러그인. tmplate에 ejs 등등의 html 템플릿 엔진으로 작성한 걸 넣어주고, filename에 그 템플릿을 토대로 새롭게 만들어질 html 파일을 지정해주면 된다.
  • clean-webpack-plugin: 배포용 파일을 빌드하기 전에 배포용 디렉토리를 지워주는 플러그인
  • extract-text-webpack-plugin: 스타일 시트를 따로 빼기 위한 플러그인
    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
    45
    46
    47
    48
    49
    50
    // webpack.config.js

    module.exports = {
    plugins: [
    // 빌드를 시작하기 전에 먼저 배포용 'build' 디렉토리를 삭제한다.
    new CleanWebpackPlugin(['build']),

    // process.env.NODE_ENV는 개발환경인지 배포환경인지 알고자 할 때 쓰인다.
    // production이면 배포 모드, development이면 개발환경이다.
    // 이는 HTML을 핫리로드하게 만들지 안 만들지를 결정하기 위해 썼다.
    new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify('production')
    }),

    // Webpack 자동 리로드
    new webpack.HotModuleReplacementPlugin(),

    // Webpack에서 필요로 하는 js 코드를 압축(난독화)
    new webpack.optimize.UglifyJsPlugin({
    compressor: {
    warnings: false,
    }
    }),

    // 모듈을 할당하고 발생 카운트 아이디들을 발생(?chunk)시킨다.
    // ID들은 종종 적은(짧은) id들을 얻는데 사용된다.
    // 이것은 id가 예상가능하며 파일 전체 크기를 경감시켜 추천한다.
    new webpack.optimize.OccurrenceOrderPlugin(),

    // HTML bundle.js 자동 삽입
    new HtmlWebpackPlugin({
    template: './src/index.html',
    minify: {
    collapseWhitespace: true,
    keepClosingSlash: true,
    removeComments: true,
    },
    xhtml: true
    }),

    // 번들링한 스타일 시트 파일을 병합/압축 및 외부파일로 내보내기
    // 내부적으로 css-loader, style-loader를 사용하여
    // 한곳에 CSS파일 코드들을 합치고 외부에 bundle.min.css 파일로 결과를 추출한다.
    new ExtractTextPlugin({
    filename: './css/bundle.min.css',
    disable: false,
    allChunks: true,
    })
    ]
    };

참조

공유하기