티스토리 뷰

Webpack :

웹팩 4 뽀개기 (개발하기 sourcemap,서버 setting(webpack dev server )


이 글은 웹팩 4 공식사이트를 번역하여 정리한 글입니다. 피드백 환영합니다!


| Using source maps

  • 웹팩이 코드를 번들링할때, 에러를 원래파일에서 트래킹하기가 어려워집니다.
  • 예를 들어, a.js ,b.js c.js라는 세가지 파일을 bundle.js라는 하나의 파일로 번들링했을때, 하나의 파일이 에러를 나타내면 에러는 단지 bundle.js파일에 에러가 있다고만 말할것입니다. 이것은 정확히 어디서 에러가 났는지 확인하지 못하게 합니다.

쉽게 에러를 트래킹하기 위해서, 자바스크립트는 source map이라는 것을 제공합니다. 컴파일 된 코드를 원래 소스코드로 맵핑을 해주는 역할을 합니다. 에러가 발생하면 b.js에서 발생했고 정확히 어디서 에러가 발생했는지 알려줍니다.


그중, inline-source-map을 사용해봅시다.


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'
    },
+   devtool: 'inline-source-map',
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Development'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

아래와 같이 cosnole이라는 오타를 내봅시다.

src/print.js

  export default function printMe() {
-   console.log('I get called from print.js!');
+   cosnole.log('I get called from print.js!');
  }

두 화면을 비교해보면 sourcemap을 사용했을시 오른쪽과 같이, 어떤 파일에서 오류가 났는지 확실하게 알려주게 됩니다.

 


Choosing a development Tool 


npm run build를 입력하여 매번 코드를 컴파일하는것은 수고롭습니다. 따라서, 자동으로 변화를 감지해 컴파일을 하는 세가지 옵션을 웹팩에서 제공하고 있습니다.


1. webpack's watch mode

2. webpack-dev-server

3. webpack-dev-middleware

대부분, webpack-dev-server를 쓴다. 하지만 모든 옵션들을 살펴보자.


1. watch mode


  • 웹팩에게 watch 명령어를 설정함으로써 모든 의존성 그래프를 계속 보고있게 한다. 만약 파일이 업데이트 되면 코드는 다시 개발자가 build 할 필요없이 자동으로 컴파일을 해준다.
  • 하지만 단점은, 터미널에서는 자동으로 컴파일 이 되는것을 확인할수있지만, 브라우저에서는 다시 refresh를 해줘야 한다.

package.json

  {
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
+     "watch": "webpack --watch",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "xml-loader": "^1.2.1"
    }
  }


2.webpack-dev-server


webpacl-dev-server는 간단한 live reloading을위한 웹서버를 제공한다.

npm install --save-dev webpack-dev-server

config 파일을 수정해서, dev server에게 어떤 파일을 볼것인지 말해준다.


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'
    },
    devtool: 'inline-source-map',
+   devServer: {
+     contentBase: './dist'
+   },
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Development'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

이 설정은 webpack-dev-server 가 dist에 있는 파일들을 serve해서 localhost:8080에서 띄워준다.

쉽게 실행하기 위해, 아래와 같이 스크립트를 넣어준다.

package.json

  {
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "watch": "webpack --watch",
+     "start": "webpack-dev-server --open",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "xml-loader": "^1.2.1"
    }
  }

npm start를 실행함으로써, 브라우저가 자동으로 코드가 변경될때마다 업데이트 되는것을 확인할 수 있다.

webpack-dev-server는 많은 configuraion 옵션이 있다. https://webpack.js.org/configuration/dev-server/ 을 참고하길 바란다.


3.webpack-dev-middleware


  • webpack-dev-middleware는 웹팩에의해 처리되는 파일들을 서버로 emit해주는 역할을 한다. 내부적으로는 webpack-dev-server에서 사용되었다. express서버를 통해 webpack-dev-middleware와 합쳐보자.
  • 아래와 같이 express와 webpack-dev-middleware를 설치해준다.
npm install --save-dev express webpack-dev-middleware

configuration 파일들을 미들웨어가 제대로 동작하도록 적절히 고쳐줘야 한다.


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'
    },
    devtool: 'inline-source-map',
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
+     publicPath: '/'
    }
  };

publicpath는 서버스크립트 내에서 사용될것이고, 정확히 http:localhost:3000 에서 실행되게 하기 위함이다. 포트넘버는 나중에 정해줄것이다.

이제 express 서버를 설정해보자.


project

  webpack-demo
  |- package.json
  |- webpack.config.js
+ |- server.js
  |- /dist
  |- /src
    |- index.js
    |- print.js
  |- /node_modules

server.js

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath
}));

// Serve the files on port 3000.
app.listen(3000, function () {
  console.log('Example app listening on port 3000!\n');
});

쉽게 서버를 작동시키기 위해 script를 추가해보자.

package.json

  {
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "watch": "webpack --watch",
      "start": "webpack-dev-server --open",
+     "server": "node server.js",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "express": "^4.15.3",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "webpack-dev-middleware": "^1.12.0",
      "xml-loader": "^1.2.1"
    }
  }

잘 실행되는것을 확인 할 수 있다.





댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2024/05   »
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
글 보관함