ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Webpack - 프로젝트 설정
    Bundler/Webpack 2021. 5. 30. 13:00
    • npm init -y
    • npm i -D webpack webpack-cli webpack-dev-server@next
      • webpack-dev-server는 webpack-cli 와 메이저 버전을 일치시켜야 하기 때문에 @next 추가
    • package.json 설정
    // package.json
    {
      "name": "webpack-bundler",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "webpack-dev-server --mode development",        // 개발용 서버 실행
        "build": "webpack --mode production"                // 빌드
      },
      "dependencies": {
        "webpack": "^5.38.1",                    // Webpack bundler를 실행하기 위한 핵심적인 패키지
        "webpack-cli": "^4.7.0",                // CLI 제공
        "webpack-dev-server": "^4.0.0-beta.3"    // 개발에 특화된 서버 사용하기 위함
      }
    }
    

    • webpack-dev-server를 통해서 개발서버를 사용하려면 구성파일 필요 (Webpack entry, output)
      • webpack.config.js 파일 생성
      • output에 path 및 filename 미지정 시
        • path는 dist 파일로 생성 (default: dist)
        • filename은 entry에 지정한 명칭과 동일하게 생성
    // webpack.config.js
    const path = require('path');
    
    // resolve(a,b): a와 b의 경로를 합쳐준다.
    // __dirname: webpack.config.js 파일이 있는 경로
    module.exports = {
      entry: './js/main.js', // 파일을 읽어들이기 시작하는 진입점 설정
      output: {
        // 결과물(번들)을 반환하는 설정
        path: path.resolve(__dirname, 'dist'), // nodejs에서 요구하는 절대경로로 지정
        filename: 'main.js',    // 빌드 파일명
        clean: true                // 재빌드 시, 필요없는 파일들 제거
      },
      resolve: {
        extensions: ['js'],
      },
    };
    

    • index.html도 build 시 포함되도록 설정 (Webpack Plugins)
      • npm i -D html-webpack-plugin
        1. html-webpack-plugin 모듈 설치
        2. webpack.config.js plugins에 추가
    // webpack.config.js
    const path = require('path');
    const HtmlPlugin = require('html-webpack-plugin');
    
    // resolve(a,b): a와 b의 경로를 합쳐준다.
    // __dirname: webpack.config.js 파일이 있는 경로
    module.exports = {
      entry: './js/main.js', // 파일을 읽어들이기 시작하는 진입점 설정
      output: {
        // 결과물(번들)을 반환하는 설정
        // path: path.resolve(__dirname, 'dist'), // nodejs에서 요구하는 절대경로로 지정
        // filename: 'main.js', // 빌드 파일명
        clean: true, // 재빌드 시, 필요없는 파일들 제거
      },
      resolve: {
        extensions: ['.wasm', '.mjs', '.js', '.jsx', '.ts', '.tsx', '.json'],
      },
      // 번들링 후 결과물의 처리 방식 등 다양한 플러그인들을 설정
      plugins: [
        new HtmlPlugin({
          template: './index.html',
        }),
      ],
      devServer: {
        host: 'localhost',
      },
    };
    

    • 정적 파일 연결 (Webpack Plugins)
      • npm i -D copy-webpack-plugin
    // webpack.config.js
    const CopyPlugin = require('copy-webpack-plugin');
    
    // resolve(a,b): a와 b의 경로를 합쳐준다.
    // __dirname: webpack.config.js 파일이 있는 경로
    module.exports = {
      plugins: [
        new HtmlPlugin({
          template: './index.html',
        }),
        new CopyPlugin({
          patterns: [{ from: 'static' }],
        }),
      ],
    };
    

    • Webpack은 CSS 파일을 읽을 수 없음 (Webpack module)
      • CSS 모듈 설치
        • npm i -D css-loader style-loader
        • css-loader : js 파일에서 css 파일을 해석하는 용도
        • style-loader : html에 style 태그를 삽입
        • 순서 중요( style-loader, css-loader )
          • 선언은 앞에서부터. 해석은 뒤에서부터

      • SCSS 모듈 설치
        • npm i -D sass-loader sass
    // webpack.config.js
    module.exports = {
      module: {
        rules: [
          {
            test: /\.s?css$/,
            use: ['style-loader', 'css-loader', 'sass-loader'],
          },
        ],
      },
    };
    

    • Autoprefixer (PostCSS)
      • npm i -D postcss autoprefixer postcss-loader
        1. webpack.config.js에 postcss-loader 추가
        2. package.json에 browserslist 추가
        3. .postcssrc.js 파일 생성 및 autoprefixer 추가
    // webpack.config.js
    module.exports = {
      module: {
        rules: [
          {
            test: /\.s?css$/,
            use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
          },
        ],
      },
    };
    
    // package.json
    {
      "name": "webpack-bundler",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "webpack-dev-server --mode development",
        "build": "webpack --mode production"
      },
      "browserslist": [
        "> 1%",
        "last 2 versions"
      ]
    }
    
    // .postcssrc.js
    module.exports = {
      plugins: [require('autoprefixer')],
    };


    • Babel
      • npm i -D @babel/core @babel/preset-env @babel/plugin-transform-runtime
      • .babelrc.js 파일 생성 및 설정
      • webpack.config.js 파일 module에 babel-loader 추가
        • npm i -D babel-loader 설치
    // .babelrc.js
    module.exports = {
      presets: ['@babel/preset-env'],
      plugins: [['@babel/plugin-transform-runtime']],
    };
    
    // webpack.config.js
    module.exports = {
      module: {
        rules: [
          {
            test: /\.s?css$/,
            use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
          },
          {
            test: /\.js$/,
            use: ['babel-loader'],
          },
        ],
      },
    };

     

    Configuration | 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

     


    • npx degit
      • degit 명령어를 이용하여 원격저장소에 있는 정보를 현재위치에 다운로드 
      • npx degit [github 원격저장소] [저장소 다운받을 폴더명]
      • 예) npx degit msko89/webpack-bundler webpack-basic

    댓글

Designed by Tistory.