GithubHelp home page GithubHelp logo

Comments (2)

hanbin9775 avatar hanbin9775 commented on June 12, 2024

Webpack의 Basic Rule

자바스크립트 코드가 많아지면 하나의 파일로 관리하는데 한계가 있다. 그렇다고 여러개 파일을 브라우져에서 로딩하는 것은 그만큼 네트웍 비용을 치뤄야하는 단점이 있다. 뿐만 아니라 각 파일은 서로의 스코프를 침범하지 않아야 하는데 잘못 작성할 경우 변수 충돌의 위험성도 있다.

함수 스코프를 사용하는 자바스크립트는 즉시호출함수(IIFE)를 사용해 모듈을 만들 수 있다. CommonJS나 AMD 스타일의 모듈 시스템을 사용하면 파일별로 모듈을 관리할 수도 있다.

그러나 여전히 브라우져에서는 파일 단위 모듈 시스템을 사용하는 것은 쉽지 않은 일이다. 모듈을 IIFE 스타일로 변경해 주는 과정 뿐만 아니라 하나의 파일로 묶어(bundled) 네트웍 비용을 최소화 할수 있는 방법이 웹 프로트엔드 개발 과정에는 필요하다.

Basic Setup

npm install webpack webpack-cli --save-dev

directory

webpack-demo
|- package.json
|- webpack.config.js
|- /dist
  |- main.js
  |- index.html
|- /src
  |- index.js
|- /node_modules

index.js

import _ from 'lodash';

function component() {
   const element = document.createElement('div');

  // Lodash, currently included via a script, is required for this line to work
  // Lodash, now imported by this script
   element.innerHTML = _.join(['Hello', 'webpack'], ' ');

   return element;
 }

 document.body.appendChild(component());

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

Before

 <!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8" />
     <title>Getting Started</title>
     <script src="https://unpkg.com/[email protected]"></script>
   </head>
   <body>
     <script src="./src/index.js"></script>
   </body>
 </html>

After

 <!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8" />
     <title>Getting Started</title>
   </head>
   <body>
     <script src="main.js"></script>
   </body>
 </html>

Entry

번들링할 최상위 모듈

Output

번들링 결과

참고 및 출처

https://webpack.js.org/
https://jeonghwan-kim.github.io/js/2017/05/15/webpack.html

from hanbin9775.github.io.

hanbin9775 avatar hanbin9775 commented on June 12, 2024

Asset Management

webpack에서 css, image와 같은 assets이 어떻게 다뤄지는지 알아보자

Loading Css

CSS 파일을 js module로 가져오려면 style-loader, css-loader 모듈이 필요하다.

npm install --save-dev style-loader css-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$/i,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
 };

모듈들은 연쇄된다. 각각 연쇄된 loader들은 다음 loader에게 변환된 결과를 넘겨준다. 따라서 위의 loader들의 순서는 지켜져야한다.
style-loader 다음에 css-loader가 와야한다.

이제 js 모듈에서 import './style.css' css 파일을 import할 수 있다.

이제 index.html에서 css link 태그를 빼주어도 된다.

Loading Image

css가 아닌 image에 대해서도 규칙을 추가해줘야한다.

다음 rule을 추가해주자

{
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
},

참고 및 출처

https://webpack.js.org/guides/asset-management/

from hanbin9775.github.io.

Related Issues (2)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.