ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TIL_201003(webpack 시작하기)
    카테고리 없음 2020. 10. 3. 16:55

     

    새로운 프로젝트를 시작하기 위해 webpack 초기 설정을 시작했습니다. 

    webpack을 사용하는 이유는 모듈 단위로 개발이 가능하고 코드를 압축/최적화할 수 있기 때문입니다. 사실 Create-React-App으로 시작한다면 기본으로 설정되어 있지만 이번에는 처음부터 설정해보려 합니다. 만들어진 대로 사용하다 보니 놓치고 있는 부분이 많다는 생각이 들었기 때문입니다. webpack 공식문서의 가이드를 차근히 따라가 보기로 합니다.

     

    webpack 시작하기

    asset 관리

     

    Loading CSS

    // CSS 파일을 추가하는 모듈 
    npm install --save-dev style-loader css-loader
    // webpack.config.js
    module.exports = {
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
      module: {
       rules: [
         {
           test: /\.css$/,
           use: [
             'style-loader',
             'css-loader',
           ],
         },
       ],
      },
    };

    위의 로더 순서를 지켜야합니다. 'style-loader'가 먼저나오고 'css-loader'가 나옵니다. 

    이제 index.js에 css파일을 import하면 됩니다.

    // src/index.js
    import './style.css';
    
    function component() {
      ...

     

    Loading Image

    // 배경, 아이콘의 이미지 모듈
    npm install --save-dev file-loader

    webpack.config.js

    const path = require('path');
    
    module.exports = {
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader'
            ],
          },
         {
           test: /\.(png|svg|jpg|gif)$/,
           use: [
             'file-loader',
           ],
         },
        ],
      },
    };

    이제 index.js 파일에 이미지를 import하면 됩니다.

    // src/index.js
    import './style.css';
    import Icon from './icon.png';
    
    function component() {
      ...

     

     

    Loading Font

    폰트를 로드하는 모듈은 file-loader이므로 webpack.config.js에 몇 줄을 추가하면 됩니다.

     

    webpack.config.js

    const path = require('path');
    
    module.exports = {
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader'
            ],
          },
         {
           test: /\.(png|svg|jpg|gif)$/,
           use: [
             'file-loader',
           ],
         },
         {
           test: /\.(woff|woff2|eot|ttf|otf)$/,
           use: [
             'file-loader',
           ],
         },
        ],
      },
    };

    그 다음 css파일에 @font-face로 폰트를 추가하면 됩니다. 여기에서 ttf나 otf 확장자의 폰트가 이상하게 적용되지 않았습니다. 밑에 나오는 예시처럼 파일을 import하지 않고 url을 추가하니 되었습니다. 아직 두가지 확장자의 파일이 왜 적용되지 않는지 확인하지 못했습니다.

    @font-face {
      font-family: 'MyFont';
      src:  url('./my-font.woff2') format('woff2'),
            url('./my-font.woff') format('woff');
      font-weight: 600;
      font-style: normal;
    }
    
    // 시도한 방식
    @font-face { 
      font-family: 'MapoGoldenPier'; 
      src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_2001@1.1/MapoGoldenPierA.woff') 
      format('woff'); 
      font-weight: normal; 
      font-style: normal; 
    }
    
    .hello {
      color: red;
      font-family: 'MyFont';
      background: url('./icon.png');
    }

     

    이외에 다음과 같은 내용이 있습니다.

    Loading Data
    Customize parser of JSON modules
    Global Assets

     

     

     

     

    Output 관리

    준비

    src 폴더 안에 print.js 파일을 추가합니다.

    project
    |- package.json
    |- webpack.config.js
    |- /dist
    |- /src
      |- index.js
      |- print.js
    |- /node_modules

    index.js 파일에 print.js를 import하고

    import print from './print.js'
    
    function component() {
      ...

    dist/index.html

    <!doctype html>
    <html>
      <head>
       <title>Output Management</title>
       <script src="./print.bundle.js"></script>
      </head>
      <body>
       <script src="./app.bundle.js"></script>
      </body>
    </html>

    그리고 webpack.config.js 파일을 바꾸고 빌드를 해봅니다.

    const path = require('path');
    
    module.exports = {
      entry: {
        app: './src/index.js',
        print: './src/print.js',
      },
      output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
    };

    dist 폴더 안에 app.bundle.js 와 print.bundle.js 파일이 생성됩니다. 그러나 webpack은 dist 폴더 안에 있는 index.html 파일은 생성하지 않습니다. 다른 파일들이 생성될때 index.html 파일도 생성되도록 하는 플러그인이 있습니다.

     

    Setting up HtmlWebpackPlugin

    npm install --save-dev html-webpack-plugin

    webpack.config.js

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: {
        app: './src/index.js',
        print: './src/print.js',
      },
      plugins: [
        new HtmlWebpackPlugin({
          title: 'Output Management',
        }),
      ],
      output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
    };

    이제 빌드를 하게 된다면 index.html이 새로 생성된 것을 볼 수 있습니다. 

     

    Cleaning up the /dist folder

    이전의 파일들이 있는 상태에서 파일이 생성되었기 때문에 폴더 안이 복잡해지기 시작합니다. 그래서 사용하지 않는 파일을 정리하기 위한 플러그인이 있습니다.

    npm install --save-dev clean-webpack-plugin

    webpack.config.js

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    
    module.exports = {
      entry: {
        app: './src/index.js',
        print: './src/print.js',
      },
      plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
          title: 'Output Management',
        }),
      ],
      output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
    };

     

     

     

     

     

     

     

     

    댓글

Designed by CHANUL