FrontEnd/프론트엔드 개발환경의 이해와 실습 (webpack, babel, esli

Webpack 심화

Tony Lim 2024. 9. 4. 11:46
728x90

webpack dev

https://webpack.js.org/configuration/dev-server/

 

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

  devServer: {
    setupMiddlewares: (middlewares, devServer) => {
      if (!devServer) {
        throw new Error('webpack-dev-server is not defined');
      }

      devServer.app.get('/setup-middleware/some/path', (_, response) => {
        response.send('setup-middlewares option GET');
      });

      // Use the `unshift` method if you want to run a middleware before all other middlewares
      // or when you are migrating from the `onBeforeSetupMiddleware` option
      middlewares.unshift({
        name: 'fist-in-array',
        // `path` is optional
        path: '/foo/path',
        middleware: (req, res) => {
          res.send('Foo!');
        },
      });

      // Use the `push` method if you want to run a middleware after all other middlewares
      // or when you are migrating from the `onAfterSetupMiddleware` option
      middlewares.push({
        name: 'hello-world-test-one',
        // `path` is optional
        path: '/foo/bar',
        middleware: (req, res) => {
          res.send('Foo Bar!');
        },
      });

      middlewares.push((req, res) => {
        res.send('Hello World!');
      });

      return middlewares;
    },
  },

일종의 mock api를 쉽게 제공해준다.

foo/path 로 가면 Foo, foo/bar로 가면 Foo Bar! 어떤 url도 matching이 되는게 업으면 Hello World이다.

unshift와 push 의 path를 같게 해도 unshift에서 먼저 request 가 resolve되어서 request-response-cycle이 끝나게 되어 push한 controller는 더 이상 실행되지 않는다. (never)

 

핫로딩은 화면전체를 refresh를 해주는것이 아니라 변경된 모듈만 replace된다.

이를 제대로 사용하기 위해서는 HMR(Hot Module Replacement) 인터페이스를 맞춰줘야한다. 

 

최적화

코드가 많아지면 번들링된 결과도 커진다. 이를 최적화하는 방법이 webpack에 존재한다.

 

production 모드

const mode = process.env.NODE_ENV || "development";

module.exports = {
  mode: mode,
  optimization: {
    minimizer: mode === "production" ? [new OptimizeCSSAssertsPlugin()] : []
  },

production 모드일 때 실행시키기를 원하는 plugin들을 배열 형식으로 추가하면 된다.

 

 

 

 

728x90