[webpack] ch10. Webpack 빌드를 위한 서버 구성
Webpack 빌드를 위한 서버 구성
webpack-dev-server
: webpack 자체에서 제공하는 개발 서버. 빠른 리로딩 기능 제공webpack-dev-middleware
: 서버가 이미 구성된 경우에는 webpack을 미들웨어로 구성하여 서버와 연결
Webpack Dev Server 소개
- 페이지 자동 고침을 제공하는 webpack 개발용 node.js 서버
설치 및 실행
- 아래 명령어로 dev-server 설치
npm install --save-dev webpack-dev-server
- 설치 후 아래 명령어로 서버 실행
webpack-dev-server --open
- 또는 package.json에 아래와 같이 명령어를 등록하여 간편하게 실행가능
"scripts": { "start": "webpack-dev-server" }
Option
publicPath
: Webpack으로 번들한 파일들이 위치하는 곳. default 값은/
// 항상 `/`를 앞뒤에 붙여야 한다. publicPath: "/assets/"
contentBase
: 서버가 로딩할 static 파일 경로를 지정. default 값은working directory
// 절대 경로를 사용할 것 contentBase: path.join(__dirname, "public") // 비활성화 contentBase: false
compress
: gzip 압축 방식을 이용하여 웹 자원의 사이즈를 줄인다.compress: true
Webpack Dev Server Setting
- webpack-dev-server 설치
(case1) npm설치 후 실행
npm install webpack webpack-dev-server --save-dev
webpack-dev-server --open
(case2) package.json에 start script 추가
"scripts": { "start": "webpack-dev-server" }
- example
- package.json 생성
- index.html 생성 ```html
hello
3. app/index.js 추가
```javascript
var ele = document.getElementsByClassName('container')[0];
ele.innerText = "Webpack loaded!!";
- Add webpack.config.js ```javascript var path = require(‘path’);
module.exports = { entry: ‘./app/index.js’, output: { filename: ‘bundle.js’, path: path.resolve(__dirname, ‘dist’), publicPath: ‘dist’ }, devtool: “cheap-eval-source-map”, devServer: { publicPath: “/dist/”, port: 9000 }, };
5. npm start를 통해 webpack-dev-server 실행
- npm start명령어로는 /dist/에 번들링파일이 생기지 않음 (In-memory에 올라감)
- 별도 파일이 필요한 경우 `webpack`명령을 통해 번들링을 따로 해야 함
## 부록 Path vs Public Path 소개
#### path vs public Path
- webpack dev server의 path, publicPath를 구분하기 위해 파악
- output의 path와 public path속성의 차이점 이해 필요
Webpack 컴파일 시에 뜨는 로그
Project is running at http://localhost:9000/ webpack output is served from /dist/
- output.path : 번들링한 결과가 위치할 번들링 파일의 절대 경로
- output.publicPath : 브라우저가 참고할 번들링 결과 파일의 URL 주소를 지정 (CDN을 사용하는 경우 CDN 호스트 지정)
```javascripot
// publicPath 예제 #1
output: {
path: "/home/proj/public/assets",
publicPath: "/assets/"
}
// publicPath 예제 #2
output: {
path: "/home/proj/cdn/assets/[hash]",
publicPath: "http://cdn.example.com/assets/[hash]"
}
// Development : Both Server and the image are on localhost
.image {
background-image: url('./test.png');
}
// Production : Server is on Heroku but the image is on a CDN
.image {
background-image: url('https://someCDN/test.png');
}
Webpack Dev Middleware
Webpack Dev Middleware 소개
- 기존에 구성한 서버에 webpack에서 컴파일한 파일을 전달하는 midware wrapper
- webpack에 설정한 파일을 변경시, 파일에 직접 변경 내역을 저장하지 않고 메모리 공간을 활용
- 따라서 변경된 파일 내역을 파일 디렉토리 구조안에서 확인 불가능
webpack-dev-middleware 설치
- npm설치 후 실행
npm install webpack --save npm install express webpack-dev-middleware --save-dev
- package.json 생성
npm init -y
- index.html 생성 ```html
hello
3. server.js 생성 및 Express 추가 및 EJS
```javascript
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname));
// view engine setup
// __dirname : root folder
app.set('views', path.join(__dirname));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.get('/', function(req, res) {
res.send('index');
});
app.listen(3000);
console.log("Server running on port 3000");
-
server.js 실행하여 에러 유무 확인
- app/index.js 추가
var ele = document.getElementsByClassName('container')[0]; ele.innerText = "Webpack loaded!!";
- webpack.config.js 추가 ```javascript var path = require(‘path’); var webpack = require(‘webpack’);
module.exports = { entry: ‘./app/index.js’, output: { filename: ‘bundle.js’, path: path.resolve(__dirname, ‘dist’), publicPath: ‘http://localhost:3000/dist’ }, };
7. server.js에 다음 코드 추가
```javascript
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpack = require("webpack");
var webpackConfig = require("./webpack.config");
var compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath,
stats: {colors: true}
}));