Mi Lugarcito

React with TypeScript - Slacks // setting (react, babel, webpack 설정편) 본문

React & Next.js

React with TypeScript - Slacks // setting (react, babel, webpack 설정편)

selene park 2021. 4. 12. 14:33

BACKEND setting

cd back -> npm i

 

backend 폴더 안에 .env

COOKIE_SECRET=sleactcookie
MYSQL_PASSWORD=1234

BACKEND db setting 

npx sequelize db:create
npm run dev했다가 ctrl + c로 끄기(테이블 생성)
npx sequelize db:seed:all(기초 데이터 넣기)
npm run dev
localhost:3095에서 서버 돌아가는 중
백엔드 개발자가 API.md와 typings/db.ts를 남겨둔 상황

 

 

 

 

Front Setting.....

TIP : npm init 할때 name명을 설치한 package 명이랑 다르게 하기

 

alecture 폴더 비우기

alecture 들어와서

cd alecture
npm init

 

1. 세팅

npm i react react-dom //react 설치
npm i typescript @types/react @types/react-dom //ts 설치

npm i -D eslint// 코드 검사 도구
npm i -D prettier eslint-plugin-prettier eslint-config-prettier //eslint 랑 prettier 연결

 

 

2. 파일 세팅하기

 

.eslintrc

{
    "extends": ["plugin:prettier/recommended"]
}

.prettierrc

{
    "printWidth": 120,
    "tabWidth": 2,
    "singleQuote": true,
    "trailingComma": "all",
    "semi": true
}

tsconfig.json

{
    "compilerOptions": {
        "esModuleInterop": true, //import React from 'react';
        "sourceMap": true,//디버깅
        "lib": ["ES2020","DOM"],//최신문법, 프런트
        "jsx":"react",//리액트 거라고 알려줌 
        "module": "esnext",//최신모듈(import, export)
        "moduleResolution": "Node",
        "target": "ES5",
        "strict": true,
        "resolveJsonModule": true,
        "baseUrl": ".",
        "paths": {//import A from @src/hello.js
            "@hooks/*" : ["hooks/*"],
            "@components/*" : ["components/*"],
            "@layouts/*" :["layouts/*"],
            "@pages/*" :["pages/*"],
            "@utils/*" :["utils/*"],
            "@typings/*":["typings/*"]
        }
    }
}

 

webpack.config.ts

import path from 'path';
//import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import webpack from 'webpack';
//import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
//import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';

const isDevelopment = process.env.NODE_ENV !== 'production';

const config: webpack.Configuration = {
  name: 'sleact',
  //배포, 개발모드
  mode: isDevelopment ? 'development' : 'production',
  //공통
  devtool: !isDevelopment ? 'hidden-source-map' : 'eval',
  resolve: {
    //바벨이 처리할 확장자 목록들
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
    //alias : 파일경로설정 때문에(TS->WEBPACK->JS)
    alias: {
      '@hooks': path.resolve(__dirname, 'hooks'),
      '@components': path.resolve(__dirname, 'components'),
      '@layouts': path.resolve(__dirname, 'layouts'),
      '@pages': path.resolve(__dirname, 'pages'),
      '@utils': path.resolve(__dirname, 'utils'),
      '@typings': path.resolve(__dirname, 'typings'),
    },
  },
  //메인파일
  entry: {
    app: './client',
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/, 
        loader: 'babel-loader',//ts,tsx 파일을 바벨 로더가 자바스크립트로 바꿔준다
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                targets: { browsers: ['last 2 chrome versions'] },
                debug: isDevelopment,
              },
            ],
            '@babel/preset-react',
            '@babel/preset-typescript',
          ]
        },
        exclude: path.join(__dirname, 'node_modules'),
      },
      {
        test: /\.css?$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  plugins: [
    // new ForkTsCheckerWebpackPlugin({
    //   async: false,
    //   // eslint: {
    //   //   files: "./src/**/*",
    //   // },
    // }),
    //공통
    new webpack.EnvironmentPlugin({ NODE_ENV: isDevelopment ? 'development' : 'production' }),
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: '/dist/',
  },
//   devServer: {
//     historyApiFallback: true, // react router
//     port: 3090,
//     publicPath: '/dist/',
//     proxy: {
//       '/api/': {
//         target: 'http://localhost:3095',
//         changeOrigin: true,
//       },
//     },
//   },
};

if (isDevelopment && config.plugins) {
//   config.plugins.push(new webpack.HotModuleReplacementPlugin());
//   config.plugins.push(new ReactRefreshWebpackPlugin());
//   config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'server', openAnalyzer: true }));
}
if (!isDevelopment && config.plugins) {
//   config.plugins.push(new webpack.LoaderOptionsPlugin({ minimize: true }));
//   config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' }));
}

export default config;

 

3. TS -> BABEL -> JS, BABEL 설정하기

webpack, webpack for bable, TypeScript  설치 및 실행하기

npm i -D webpack @babel/core babel-loader @babel/preset-env @babel/preset-react //공통 필수
npm i -D @types/webpack @types/node @babel/preset-typescript//타입스크립트를 위해서
npm i style-loader css-loader

 

 

index.html (dist 폴더는 webpack 설정할때 생긴다!)

<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>슬리액</title>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            overflow: initial !important;
        }
        body {
            font-size: 15px;
            line-height: 1.46668;
            font-weight: 400;
            font-variant-ligatures: common-ligatures;
            -moz-osx-font-smoothing: grayscale;
            -webkit-font-smoothing: antialiased;
        }
        * {
            box-sizing: border-box;
        }
    </style>
    <link rel="stylesheet" href="https://a.slack-edge.com/bv1-9/client-boot-styles.dc0a11f.css?cacheKey=gantry-1613184053" crossorigin="anonymous" />
    <link rel="shortcut icon" href="https://a.slack-edge.com/cebaa/img/ico/favicon.ico" />
    <link href="https://a.slack-edge.com/bv1-9/slack-icons-v2-16ca3a7.woff2" rel="preload" as="font" crossorigin="anonymous" />
  </head>
  <body>
    <div id="app">
        
    </div>
    <script src="./dist/app.js"></script>
  </body>
</html> 

client.tsx

import React from 'react';
import { render } from 'react-dom';
import App from './layouts/App';

render(<App/>, document.querySelector('#app'));

 

alecture / layouts 폴더/App.tsx

import React from 'react';

const App=()=>{
    return <div>배고파.....</div>;
};

export default App;

 

tsconfig-for-webpack-config.json 

{
    "compilerOptions": {
        "module" : "CommonJS",
        "moduleResolution": "Node",
        "target": "ES5",
        "esModuleInterop": true
    }
}

 

 

package.json 파일에 아래 추가하기 (webpack 명령어로 간편하게 설치 및 사용하기 위해서)

"build":"TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" webpack"

 

 

npm run build

 

 

webpack 까지 설치 완료가 되면! 아래와 같이 dist 폴더안에 app.js 파일이 자동 생성됨!

 

 

index.html 에 돌아와서 라이브 서버 키고

 

아래의 화면 순서대로 실행됨