#react
#pwa
#webpack
Written by Paul
React를 Webpack으로 설정하기
1. 모듈 추가
src
디렉토리 생성
public
디렉토리 생성
- ES6 모듈 추가
yarn add -D @babel/core @babel/preset-env @babel/preset-react
2. Webpack 모듈 설치
yarn add -D webpack webpack-cli webpack-dev-server babel-loader css-loader style-loader html-webpack-plugin
3. webpack.config.js 설정
webpack.config.js
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const htmlPlugin = new HtmlWebpackPlugin({ template: './public/index.html', filename: './index.html', }) const config = mode => { const isDevelopMode = mode === 'development' return { entry: './src/index.js', output: { path: path.join(__dirname, '/build'), filename: 'index.bundle.js', }, module: { rules: [ { test: /\\\\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', }, }, { test: /\\\\.(css)$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { modules: { localIdentName: isDevelopMode ? '[path][name]__[local]--[hash:base64:5]' : '[name]__[local]--[hash:base64:5]', }, importLoaders: 1, sourceMap: true, }, }, ], }, ], }, plugins: [htmlPlugin], } } module.exports = (env, argv) => { const { mode } = argv return config(mode) }
4. public 디렉토리에 index.html 추가
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>React PWA Webpack</title> </head> <body> <div id="root"></div> </body> </html>
5. Babel 설정
.babelrc
{ "presets": ["@babel/env", "@babel/react"] }
6. React 설치
yarn add react react-dom
7. src/index.js 생성
src/index.js
import React from 'react' import ReactDOM from 'react-dom' const Root = () => <div>Hello World!</div> ReactDOM.render(<Root />, document.getElementById('root'))
8. package.json 스크립트 추가
package.json
"scripts": { "build:prod": "webpack --mode=production", "build:dev": "webpack --mode=development" }
9. 핫 리로드가 가능한 개발 서버 설정
package.json
"scripts": { "start:dev": "webpack-dev-server --mode=development --open --hot" }