react + tailwind css + ts 구성하기

katanazero·2022년 1월 4일
1

react

목록 보기
11/15
post-custom-banner

react + tailwind css + ts 프로젝트 구성하기

  • CRA(Create React App)를 활용해서 프로젝트를 빠르게 구성하여 사용이 가능하나, 만약 설정관련하여 좀 더 자유로움을 얻고자하신다면 참고해주시길 바랍니다.(더불어 설정하면서 원리도 이해하면 좋구요)

  1. node.js 설치 및 npm 설치

  2. 프로젝트 생성
    빈 프로젝트를 생성하여, 아래 명령어를 실행하여 package.json 을 생성해주자.
    npm init -y
    -y 옵션은 default 로 생성하겠다는 의미다.

  1. 관련 node module 을 하나하나 설치를 해주자.
react
react-dom

webpack
webpack-cli
webpack-dev-server
style-loader
css-loader
html-webpack-plugin
copy-webpack-plugin
clean-webpack-plugin
mini-css-extract-plugin
sass
sass-loader

@babel/core
@babel/preset-env
@babel/preset-react
babel-loader

npm i react react-dom
npm i -D webpack webpack-cli webpack-dev-server style-loader css-loader html-webpack-plugin copy-webpack-plugin clean-webpack-plugin mini-css-extract-plugin sass sass-loader
npm i -D @babel/core @babel/preset-env @babel/preset-react babel-loader

  1. root path 에 webpack.config.js.babelrc 파일을 생성 및 설정작성
  • .babelrc
    해당 파일은 babel 설정 파일입니다.
    @babel/preset-react 의 runtime 옵션을 automatic 으로 설정해야합니다.(기본값은 classic)
    저같은 경우는 react is not defined 에러가 발생하였습니다. 아마 최신버전 이슈인거 같습니다.
{
  "presets": [
    "@babel/preset-env",
    [
      "@babel/preset-react",
      {
        "runtime": "automatic"
      }
    ]
  ],
  "plugins": []
}
  • webpack.config.js
    해당 파일은 webpack 설정 파일입니다.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = function (env, argv) {

    console.log(env);

    const isEnvDevelopment = env?.NODE_ENV === 'development';
    const isEnvProduction = env?.NODE_ENV === 'production';

    const babelLoaderRegExp = /\.(js|jsx)$/;
    const cssRegExp = /\.(css|scss)$/i;
    const cssModuleRegExp = /\.module\.(css|scss)$/;

    const cssLoaderOptions = {
        importLoaders: 1,
        sourceMap: isEnvDevelopment,
    };
    const cssLoaderOptionsForModule = {
        importLoaders: 1,
        sourceMap: isEnvDevelopment,
        modules: true,
    };
    const sassLoaderOptions = {
        sassOptions: {
            indentWidth: 4,
            sourceMap: isEnvDevelopment,
            outputStyle: 'compressed',
        },
    };

    return {
        mode: isEnvProduction ? 'production' : 'development',
        entry: path.resolve(__dirname, 'src/index.js'),
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js',
            publicPath: '/',
        },
        module: {
            rules: [
                {
                    test: babelLoaderRegExp,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader",
                    },
                },
                {
                    test: cssRegExp,
                    exclude: cssModuleRegExp,
                    use: [MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: cssLoaderOptions,
                        },
                        {
                            loader: 'sass-loader',
                            options: sassLoaderOptions,
                        },],
                },
                {
                    test: cssRegExp,
                    include: cssModuleRegExp,
                    use: [MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: cssLoaderOptionsForModule
                        },
                        {
                            loader: 'sass-loader',
                            options: sassLoaderOptions,
                        },],
                },
            ],
        },
        devServer: {
            port: 3000,
            liveReload: true,
        },
        devtool: isEnvProduction ? 'source-map' : 'eval',
        plugins: [
            new CleanWebpackPlugin(),
            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: './public/index.html'
            }),
            new MiniCssExtractPlugin({
                filename: 'static/css/[name].[contenthash:8].css',
            }),
            new CopyWebpackPlugin({
                patterns: [
                    {
                        from: path.resolve(__dirname, 'public/static'),
                        to: path.resolve(__dirname, 'dist/static'),
                        noErrorOnMissing: true
                    },
                ],
            }),
        ],
    }
}
  1. package.json 스크립트 영역에 아래와 같이 작성해줍니다.

"dev": "webpack serve --env NODE_ENV=development --hot --open"

  1. 기본적인 실행을 위해, 파일들을 작성해줍니다.
/public/index.html
/src/App.js
/src/App.scss
/src/index.js
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>React + tailwind css + ts</title>
</head>
<body>
<main id="app"></main>
</body>
</html>
import './App.scss';

export default function App() {
    return (
        <div className="app">
            hello
        </div>
    );
}
$color-red: red;

.app {
    font-size: 20px;
    letter-spacing: 0.5px;
    text-align: center;
    color: $color-red;
}
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App/>, document.getElementById('app'));

여기까지 오시느라 힘드셨죠? 이제 실행해 봅시다.

이제 ts 와 tailwind css 를 설정해보도록 하겠습니다.

npm i -D @babel/preset-typescript
npm i -D typescript ts-loader @types/react @types/react-dom

tsc --init // tsconfig.js create

.babelrc 수정

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript",
    [
      "@babel/preset-react",
      {
        "runtime": "automatic"
      }
    ]
  ],
  "plugins": []
}

tsconfig.js
타입스크립트 설정 파일입니다

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Enable incremental compilation */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "ESNext",
    /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    "jsx": "react",
    /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
    // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */

    /* Modules */
    "module": "commonjs",
    /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    "baseUrl": "./src",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "resolveJsonModule": true,                        /* Enable importing .json files */
    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    "sourceMap": true,
    /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,
    /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,
    /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,
    /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
    // "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
    // "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true
    /* Skip type checking all .d.ts files. */
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

webpack.config.js 도 내용을 조금 수정하였습니다.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = function (env, argv) {

    console.log(env);

    const isEnvDevelopment = env?.NODE_ENV === 'development';
    const isEnvProduction = env?.NODE_ENV === 'production';

    const babelLoaderRegExp = /\.(js|jsx|ts|tsx)$/;
    const cssRegExp = /\.(css|scss)$/i;
    const cssModuleRegExp = /\.module\.(css|scss)$/;

    const cssLoaderOptions = {
        importLoaders: 1,
        sourceMap: isEnvDevelopment,
    };
    const cssLoaderOptionsForModule = {
        importLoaders: 1,
        sourceMap: isEnvDevelopment,
        modules: true,
    };
    const sassLoaderOptions = {
        sassOptions: {
            indentWidth: 4,
            sourceMap: isEnvDevelopment,
            outputStyle: 'compressed',
        },
    };

    return {
        mode: isEnvProduction ? 'production' : 'development',
        entry: path.resolve(__dirname, 'src/index.js'),
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js',
            publicPath: '/',
        },
        resolve: {
            enforceExtension: false,
            extensions: ['.js', '.jsx', '.ts', '.tsx'],
        },
        module: {
            rules: [
                {
                    test: babelLoaderRegExp,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader",
                    },
                },
                {
                    test: cssRegExp,
                    exclude: cssModuleRegExp,
                    use: [MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: cssLoaderOptions,
                        },
                        {
                            loader: 'sass-loader',
                            options: sassLoaderOptions,
                        },],
                },
                {
                    test: cssRegExp,
                    include: cssModuleRegExp,
                    use: [MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: cssLoaderOptionsForModule
                        },
                        {
                            loader: 'sass-loader',
                            options: sassLoaderOptions,
                        },],
                },
            ],
        },
        devServer: {
            port: 3000,
            liveReload: true,
        },
        devtool: isEnvProduction ? 'source-map' : 'eval',
        plugins: [
            new CleanWebpackPlugin(),
            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: './public/index.html'
            }),
            new MiniCssExtractPlugin({
                filename: 'static/css/[name].[contenthash:8].css',
            }),
            new CopyWebpackPlugin({
                patterns: [
                    {
                        from: path.resolve(__dirname, 'public/static'),
                        to: path.resolve(__dirname, 'dist/static'),
                        noErrorOnMissing: true
                    },
                ],
            }),
        ],
    }
}

HelloComponent.tsx 파일을 작성하여, 잘 동작하는지 확인해 보겠습니다.

import React, {useState} from 'react';

export default function HelloComponent(): React.ReactElement {

    const msg = useState<string | null>('ts hello world');

    return (
        <div>
            {msg}
        </div>
    )
}

성공입니다. 이제 tailwind css 만 설정하면 끝납니다.


npm i -D tailwindcss postcss autoprefixer
npm i -D postcss-loader
npx tailwindcss init  // crete tailwind.config.js
npx tailwindcss init -p // create tailwind.config.js, postcss.config.js
  • tailwind.config.js
module.exports = {
  content: [],
  theme: {
    extend: {},
  },
  plugins: [],
}
  • postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}
  • src/ 경로에 아래와 같은 내용을 담고있는 css 파일을 작성해주시고 index.js 를 수정해줍니다.
@tailwind base;
@tailwind components;
@tailwind utilities;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

import './tailwind/tailwind.index.css';

ReactDOM.render(<App/>, document.getElementById('app'));

App 컴포넌트에 아래와 같은 마크업을 추가해주고 실행을 해보면..!

<h1 className="text-3xl font-bold underline text-blue-500">
                Hello world!(tailwind css)
</h1>

위와 같이 뜨면 정상적으로 적용이 된겁니다.

읽어주셔서 감사합니다!


하지만..
라우터, 스토어, lint, prettier 까지 한다면.. ~_~...읔😂😂

profile
developer life started : 2016.06.07 ~ 흔한 Front-end 개발자
post-custom-banner

0개의 댓글