react (cra) - webpack 커스텀 react-app-rewired (pc, wv 분리)
개요)
create react app 으로 만든
spa 리액트 프로젝트는 webpack이 내장되어 있다.
따로 커스텀 할 수 없다.
나는 빌드시 mobile, pc용 각각 빌드하길 원해서custom 할 방법을 찾아봤는데크게 3가지가 있었다.
하나씩 모두 테스트 해보았는데
라이브러리 ' react-app-rewired ' 로 선택함
https://www.npmjs.com/package/react-app-rewired
react-app-rewired
Tweak the create-react-app webpack config(s) without using 'eject' and without creating a fork of the react-scripts. Latest version: 2.2.1, last published: 3 years ago. Start using react-app-rewired in your project by running `npm i react-app-rewired`. The
www.npmjs.com
1. 라이브러리 설치
npm install react-app-rewired --save-dev
2. webpack 설정 override 할 파일 생성
설정 파일은
현재 작업 소스 기준으로 되어있다.
라이브러리 페이지에 가면
다양한 옵션이 있으니 확인하기
[config-overrides.js]
// config-overrides.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const multipleEntry = require('react-app-rewire-multiple-entry')([
{
// Webpack extra entry
entry: './src/index.js',
// HTML template used in plugin HtmlWebpackPlugin
template: './public/index.html',
// The file to write the HTML to. You can specify a subdirectory
outPath: '/pc.html'
// Visit: http[s]://localhost:3000/entry/standard.html
},
{
entry: './src/mobile.js',
// if [template] is empty, Default value: `public/index.html`
// template: 'public/index.html',
template: './public/mobile.html',
outPath: './mobile.html'
// Visit: http[s]://localhost:3000/public/login.html
},
]);
module.exports = {
webpack: function(config, env) {
multipleEntry.addMultiEntry(config);
// 간접경로 사용을 피하기 위해 디렉토리 alias 설정
config.resolve.alias = {
...(config.resolve.alias || {}),
'@': path.resolve(__dirname, 'src')
};
/**
* *** start) 모바일 작업시 활성화 시키기
*/
/*
config.entry = path.resolve(__dirname, 'src/mobile.js');
config.plugins = config.plugins.map((plugin) => {
if (plugin instanceof HtmlWebpackPlugin) {
return new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'public/mobile.html'),
inject: true,
});
}
return plugin;
});
*/
// *** end) mobile로 열 때 활성화 시키기
return config;
}
};
3. react-app-rewired 라이브러리로 서버 실행할 수 있도록 스크립트 수정
[package.json]
// ....생략
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject",
"format": "prettier --check ./src",
"format:fix": "prettier --write ./src",
"prepare": "husky"
},
// ....생략
npm run build를 통해
빌드된 내용을 확인하면
나눠서 빌드된 것을 확인할 수 있다.
다음 내용으로는
nginx에서
mobile.html, pc.html을
서빙해줄 수 있는지 정리