Webpack부터 TypeScript React환경을 만들기_1
프로젝트 준비
1
2
3
4
mkdir react_template #개발환경을 구성할 디렉토리를 생성합니다.
cd react_template
mkdir build #빌드 되어진 파일들이 저장되는 디렉토리를 생성합니다.
mkdir src #실질적인 코드를 작성하는 파일들을 저장하는 디렉토리를 생성합니다.
프로젝트에 필요한 라이브러리 설치
1
2
git init #git을 초기화 합니다.
npm init -y #npm 초기 설정을 합니다.
Index.html등록
1
2
cd src
vim index.html #시스템의 시작이되는 index.html를 생성
Index.html
1
2
3
4
5
6
7
8
9
10
11
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typescript React</title>
</head>
<body>
</body>
</html>
gitIgnore설정
1
2
3
4
5
6
cd ..
vim .gitignore
# .gitignore start
build #빌드 되어진 파일을 무시
node_modules #저장된 외부 패키지들을 무시
# .gitignore end
패키지 설치
1
2
yarn add react react-dom #react 기본 패키지 설치
yarn add typescript @types/react @types/react-dom #typescript 및 react 와 typescript를 연결하기위한 패키지 설치
tsconfig.json 등록
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
vim tsconfig.json
### tsconfig.json start
{
"compilerOptions": {
"target": "ES5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ /* Type declaration files to be included in compilation. */,
"lib": [
"DOM",
"ESNext"
] /* Specify library files to be included in the compilation. */,
"jsx": "react-jsx" /* Specify JSX code generation: 'preserve', 'react-native', 'react' or 'react-jsx'. */,
"noEmit": true /* Do not emit outputs. */,
"isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"strict": true /* Enable all strict type-checking options. */,
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
"resolveJsonModule": true
// "allowJs": true /* Allow javascript files to be compiled. Useful when migrating JS to TS */,
// "checkJs": true /* Report errors in .js files. Works in tandem with allowJs. */,
},
"include": ["src/**/*"]
}
### tsconfig.json End
App.tsx작성
1
2
3
4
5
//index.html에 출력을위한 App.tsx를 작성
//src디렉토리에 생성
export const App = () => {
return <h1>React TypeScript Webpack Starter Template</h1>
}
index.tsx작성
1
2
3
4
5
6
// react의 시작이되는 index.tsx를 작성
// src디렉토리에 작성
import ReactDOM from 'react-dom'
import { App } from './App'
ReactDOM.render(<App />, document.getElementById('root'))
Babel패키지 설치 및 .babelrc설정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
yarn add -D @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript
# 개발환경 root디렉토리에 .babelrc저장
vim .babelrc
# .babelrc Start
{
"presets": [
"@babel/preset-env",
[
"@babel/preset-react",
{
"runtime": "automatic"
}
],
"@babel/preset-typescript"
]
}
Wepack패키지 설치
1
2
3
4
5
6
7
8
# webpack, webpack 커맨드라인, webpack 개발용 서버, webpack에서 html인식 패키지 설치
yarn add -D webpack webpack-cli webpack-dev-server html-webpack-plugin
# webpack에서 babel를 읽어오기위한 패키지
yarn add -D babel-loader
# 개발 root디렉토리에서 webpack폴더 생성
mkdir webpack
cd webpack
vim webpack.config.js
Webpack.config.js작성
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
32
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.tsx'),
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
reules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
],
},
output: {
path: path.resolve(__dirname, '..', './build'),
filename: 'bundle.js',
},
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '..', './src/index.html'),
}),
],
}
Package.json 실행 스크립트 추가 및 테스트
1
2
3
4
5
6
7
#개발환경root디렉토리에있는 package.json에서 scripts부분에 추가
# package.json 의 scripts부분 Start
"start": "webpack serve --config webpack/webpack.config.js --open",
# package.json 의 scripts부분 End
# 테스트
yarn start
React에서 Style적용하기
1
2
3
4
5
6
/* src디렉토리에 style.css생성 */
/* style start */
h1 {
color: orange; /* h1태그에있는 문자의 색을 오랜지 색으로 바꿈 */
}
/* style end */
기존 App.tsx 수정
1
2
3
4
5
import './style.css'
export const App = () => {
return <h1>React TypeScript Webpack Starter Template</h1>;
};
- 위의 style.css파일 추가 및
import './style.css'
를 추가만으로는 실질적으로 반영이 되지 않습니다. 반영을 시키기 위해서는 webpack에서 style를 인식 시켜줘야 합니다.
스타일을 위한 패키지 추가 및 webpack.config.js수정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
yarn add -D css-loader style-loader
#webpack.config.js 의 rules부분을 이하와 같이 수정
rules : [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
]
시스템에 이미지 반영
1
2
3
4
5
6
7
8
9
10
11
12
13
#이미지 파일을 src디렉토리에 추가 합니다. (예제의 경우 react.png를 추가)
#추가된 이미지파일을 인식 시키기 위해 src디렉토리에 declarations.d.ts 생성 및 이미지에대한 확장자를 선언해야합니다.
### declarations.d.ts Start
declare module '*.png'
### declarations.d.ts End
# webpack.config.js 또한 image파일을 인식시키기 위한 코드를 추가
# rules에 추가
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
이미지를 App.tsx에 추가
1
2
3
4
5
6
7
8
9
10
import "./style.css";
import IMAGE from "./react.png";
export const App = () => {
return (
<>
<h1>React TypeScript Webpack Starter Template</h1>
<img src={IMAGE} alt="react logo" width="300" height="200" />
</>
);
};
SVG이미지 파일 추가
1
2
3
4
5
6
7
8
9
10
11
12
# logo.svg파일을 src디렉토리에 추가
# 이미지파일 과 동일하게 declarations.d.ts 에 svg확장자 추가
### declarations.d.ts Start
declare module '*.svg'
### declarations.d.ts End
# webpack.config.js의 rules에 추가
{
test: /\.(woff(2)?|eot|ttf|otf|svg)$/,
type: 'asset/inline',
},
App.tsx에 svg이미지 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
import "./style.css";
import IMAGE from "./react.png";
import LOGO from "./logo.svg";
export const App = () => {
return (
<>
<h1>React TypeScript Webpack Starter Template</h1>
<img src={IMAGE} alt="react logo" width="300" height="200" />
<img src={LOGO} alt="react logo" width="300" height="200" />
</>
);
};