├── .all-contributorsrc ├── .eslintignore ├── .eslintrc.js ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── feature_request.md │ └── question.md ├── PULL_REQUEST_TEMPLATE.md ├── dependabot.yml └── workflows │ ├── ci.yml │ └── codeql-analysis.yml ├── .gitignore ├── .husky ├── pre-commit └── pre-push ├── .prettierignore ├── .stylelintrc.js ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── babel.config.js ├── jest ├── assetMock.ts ├── config.js ├── setup.ts └── styleMock.ts ├── nodemon.json ├── package.json ├── postcss.config.js ├── public ├── favicon.ico ├── logo192.png ├── logo512.png └── manifest.json ├── src ├── app │ ├── __tests__ │ │ ├── App.tsx │ │ └── __snapshots__ │ │ │ └── App.tsx.snap │ ├── index.tsx │ └── styles.module.scss ├── client │ └── index.tsx ├── components │ ├── ErrorBoundary │ │ ├── __tests__ │ │ │ ├── ErrorBoundary.tsx │ │ │ └── __snapshots__ │ │ │ │ └── ErrorBoundary.tsx.snap │ │ └── index.tsx │ ├── Info │ │ ├── __tests__ │ │ │ ├── Info.tsx │ │ │ └── __snapshots__ │ │ │ │ └── Info.tsx.snap │ │ ├── index.tsx │ │ └── styles.module.scss │ ├── List │ │ ├── __tests__ │ │ │ ├── List.tsx │ │ │ └── __snapshots__ │ │ │ │ └── List.tsx.snap │ │ ├── index.tsx │ │ └── styles.module.scss │ ├── Loading │ │ ├── __tests__ │ │ │ ├── Loading.tsx │ │ │ └── __snapshots__ │ │ │ │ └── Loading.tsx.snap │ │ ├── index.tsx │ │ └── styles.module.scss │ └── index.ts ├── config │ ├── default.ts │ ├── index.ts │ └── prod.ts ├── pages │ ├── Home │ │ ├── Home.tsx │ │ ├── __tests__ │ │ │ ├── Home.tsx │ │ │ └── __snapshots__ │ │ │ │ └── Home.tsx.snap │ │ ├── index.tsx │ │ └── styles.module.scss │ ├── NotFound │ │ ├── __tests__ │ │ │ ├── NotFound.tsx │ │ │ └── __snapshots__ │ │ │ │ └── NotFound.tsx.snap │ │ ├── index.tsx │ │ └── styles.module.scss │ └── UserInfo │ │ ├── UserInfo.tsx │ │ ├── __tests__ │ │ ├── UserInfo.tsx │ │ └── __snapshots__ │ │ │ └── UserInfo.tsx.snap │ │ ├── index.tsx │ │ └── styles.module.scss ├── routes │ └── index.ts ├── server │ ├── devServer.ts │ ├── index.ts │ ├── renderHtml.ts │ └── ssr.tsx ├── services │ └── jsonPlaceholder.ts ├── static │ └── logo.svg ├── store │ ├── __tests__ │ │ ├── userData.ts │ │ └── userList.ts │ ├── index.ts │ ├── rootReducer.ts │ ├── userData.ts │ └── userList.ts ├── theme │ └── variables.scss ├── types │ └── index.d.ts └── utils │ └── mockStore.tsx ├── tsconfig.json ├── webpack ├── base.config.ts ├── client.config.ts └── server.config.ts └── yarn.lock /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "README.md" 4 | ], 5 | "imageSize": 100, 6 | "commit": false, 7 | "contributors": [ 8 | { 9 | "login": "wellyshen", 10 | "name": "Welly", 11 | "avatar_url": "https://avatars1.githubusercontent.com/u/21308003?v=4", 12 | "profile": "https://wellyshen.com", 13 | "contributions": [ 14 | "code", 15 | "doc", 16 | "maintenance" 17 | ] 18 | }, 19 | { 20 | "login": "Microflow", 21 | "name": "Microflow", 22 | "avatar_url": "https://avatars1.githubusercontent.com/u/15410443?v=4", 23 | "profile": "https://github.com/Microflow", 24 | "contributions": [ 25 | "translation" 26 | ] 27 | }, 28 | { 29 | "login": "jabacchetta", 30 | "name": "Jason Bacchetta", 31 | "avatar_url": "https://avatars0.githubusercontent.com/u/12591890?v=4", 32 | "profile": "http://bacchetta.co/", 33 | "contributions": [ 34 | "tool" 35 | ] 36 | }, 37 | { 38 | "login": "xakep139", 39 | "name": "Nikita Balabaev", 40 | "avatar_url": "https://avatars2.githubusercontent.com/u/6381023?v=4", 41 | "profile": "https://github.com/xakep139", 42 | "contributions": [ 43 | "code" 44 | ] 45 | }, 46 | { 47 | "login": "jmsherry", 48 | "name": "James Sherry", 49 | "avatar_url": "https://avatars1.githubusercontent.com/u/697341?v=4", 50 | "profile": "https://github.com/jmsherry", 51 | "contributions": [ 52 | "infra", 53 | "bug" 54 | ] 55 | }, 56 | { 57 | "login": "zace", 58 | "name": "Zack Pelz", 59 | "avatar_url": "https://avatars0.githubusercontent.com/u/3301615?v=4", 60 | "profile": "https://github.com/zace", 61 | "contributions": [ 62 | "translation" 63 | ] 64 | }, 65 | { 66 | "login": "apapacy", 67 | "name": "apapacy", 68 | "avatar_url": "https://avatars3.githubusercontent.com/u/4279840?v=4", 69 | "profile": "https://github.com/apapacy", 70 | "contributions": [ 71 | "code" 72 | ] 73 | }, 74 | { 75 | "login": "martin2786", 76 | "name": "martin2786", 77 | "avatar_url": "https://avatars3.githubusercontent.com/u/2111808?v=4", 78 | "profile": "https://github.com/martin2786", 79 | "contributions": [ 80 | "doc" 81 | ] 82 | }, 83 | { 84 | "login": "iamacup", 85 | "name": "iamacup", 86 | "avatar_url": "https://avatars2.githubusercontent.com/u/12894620?v=4", 87 | "profile": "https://github.com/iamacup", 88 | "contributions": [ 89 | "tool" 90 | ] 91 | }, 92 | { 93 | "login": "forwardomg", 94 | "name": "Maxim", 95 | "avatar_url": "https://avatars1.githubusercontent.com/u/5165362?v=4", 96 | "profile": "http://zhogov.me/", 97 | "contributions": [ 98 | "tool" 99 | ] 100 | }, 101 | { 102 | "login": "bennyn", 103 | "name": "Benny Neugebauer", 104 | "avatar_url": "https://avatars3.githubusercontent.com/u/469989?v=4", 105 | "profile": "http://stackoverflow.com/users/451634/benny-neugebauer", 106 | "contributions": [ 107 | "translation" 108 | ] 109 | }, 110 | { 111 | "login": "aslapkov", 112 | "name": " A. S. Lapkov", 113 | "avatar_url": "https://avatars2.githubusercontent.com/u/12545211?v=4", 114 | "profile": "https://lapkov.com", 115 | "contributions": [ 116 | "code" 117 | ] 118 | }, 119 | { 120 | "login": "alirezavalizade", 121 | "name": "Alireza Valizade", 122 | "avatar_url": "https://avatars0.githubusercontent.com/u/14992757?v=4", 123 | "profile": "https://github.com/alirezavalizade", 124 | "contributions": [ 125 | "code" 126 | ] 127 | }, 128 | { 129 | "login": "Rid", 130 | "name": "Grant Millar", 131 | "avatar_url": "https://avatars2.githubusercontent.com/u/3407496?v=4", 132 | "profile": "https://github.com/Rid", 133 | "contributions": [ 134 | "bug", 135 | "code" 136 | ] 137 | }, 138 | { 139 | "login": "BJvdA", 140 | "name": "Bart", 141 | "avatar_url": "https://avatars3.githubusercontent.com/u/9120530?v=4", 142 | "profile": "https://github.com/BJvdA", 143 | "contributions": [ 144 | "bug" 145 | ] 146 | }, 147 | { 148 | "login": "MortezaT", 149 | "name": "Morteza Tourani", 150 | "avatar_url": "https://avatars2.githubusercontent.com/u/2953251?v=4", 151 | "profile": "https://stackoverflow.com/users/3078890/morteza-tourani", 152 | "contributions": [ 153 | "code" 154 | ] 155 | }, 156 | { 157 | "login": "tomkiernan120", 158 | "name": "Tom Kiernan", 159 | "avatar_url": "https://avatars2.githubusercontent.com/u/13321712?v=4", 160 | "profile": "http://www.tomkiernan.co.uk", 161 | "contributions": [ 162 | "translation" 163 | ] 164 | }, 165 | { 166 | "login": "xD3CODER", 167 | "name": "Nathan KREMER", 168 | "avatar_url": "https://avatars0.githubusercontent.com/u/14862690?v=4", 169 | "profile": "https://nkremer.fr", 170 | "contributions": [ 171 | "code" 172 | ] 173 | }, 174 | { 175 | "login": "amerllica", 176 | "name": "Amer Lotfi Orimi", 177 | "avatar_url": "https://avatars0.githubusercontent.com/u/10472437?v=4", 178 | "profile": "https://twitter.com/amerllica", 179 | "contributions": [ 180 | "tool", 181 | "code" 182 | ] 183 | }, 184 | { 185 | "login": "w3debugger", 186 | "name": "Muhammad Umar", 187 | "avatar_url": "https://avatars2.githubusercontent.com/u/6707482?v=4", 188 | "profile": "https://w3debugger.com", 189 | "contributions": [ 190 | "code" 191 | ] 192 | }, 193 | { 194 | "login": "denny64", 195 | "name": "Denny Vuong", 196 | "avatar_url": "https://avatars1.githubusercontent.com/u/9099997?v=4", 197 | "profile": "https://github.com/denny64", 198 | "contributions": [ 199 | "doc", 200 | "code" 201 | ] 202 | }, 203 | { 204 | "login": "mattcarlotta", 205 | "name": "Matt Carlotta", 206 | "avatar_url": "https://avatars1.githubusercontent.com/u/22607722?v=4", 207 | "profile": "https://mattcarlotta.io", 208 | "contributions": [ 209 | "code" 210 | ] 211 | } 212 | ], 213 | "contributorsPerLine": 7, 214 | "projectName": "react-cool-starter", 215 | "projectOwner": "wellyshen", 216 | "repoType": "github", 217 | "repoHost": "https://github.com", 218 | "skipCi": true 219 | } 220 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | public 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: "@typescript-eslint/parser", 3 | extends: [ 4 | "airbnb", 5 | "airbnb/hooks", 6 | "plugin:@typescript-eslint/recommended", 7 | "plugin:jest/recommended", 8 | "plugin:jest/style", 9 | "plugin:jest-dom/recommended", 10 | "plugin:testing-library/react", 11 | "prettier", 12 | ], 13 | plugins: ["@typescript-eslint", "jest", "jest-dom", "testing-library"], 14 | settings: { 15 | "import/resolver": { 16 | typescript: {}, 17 | }, 18 | }, 19 | env: { 20 | browser: true, 21 | node: true, 22 | es6: true, 23 | jest: true, 24 | }, 25 | rules: { 26 | "global-require": "off", 27 | "no-use-before-define": "off", 28 | "no-console": "off", 29 | "no-underscore-dangle": "off", 30 | "no-param-reassign": "off", 31 | "react/react-in-jsx-scope": "off", 32 | "react/jsx-props-no-spreading": "off", 33 | "react/jsx-filename-extension": [ 34 | "error", 35 | { 36 | extensions: [".js", ".jsx", ".ts", ".tsx"], 37 | }, 38 | ], 39 | "import/extensions": "off", 40 | "import/no-extraneous-dependencies": [ 41 | "error", 42 | { 43 | devDependencies: true, 44 | }, 45 | ], 46 | "@typescript-eslint/ban-ts-comment": "off", 47 | "@typescript-eslint/no-explicit-any": "off", 48 | "@typescript-eslint/no-var-requires": "off", 49 | "testing-library/no-node-access": "off", 50 | "testing-library/render-result-naming-convention": "off", 51 | }, 52 | globals: { 53 | __CLIENT__: true, 54 | __SERVER__: true, 55 | __DEV__: true, 56 | }, 57 | }; 58 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: react-cool-starter 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F41B Bug Report" 3 | about: Create a report to help us improve 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | # Bug Report 10 | 11 | ## Describe the Bug 12 | 13 | A clear and concise description of what the bug is. 14 | 15 | ## How to Reproduce 16 | 17 | Steps to reproduce the behavior, please provide code snippets or a repository: 18 | 19 | 1. Go to '....' 20 | 2. Click on '....' 21 | 3. See error 22 | 23 | ## Expected Behavior 24 | 25 | Tell me what should happen. 26 | 27 | ## Screenshots 28 | 29 | Add screenshots to help explain your problem. 30 | 31 | ## Your Environment 32 | 33 | - Device: [e.g. MacBook Pro, iPhone12] 34 | - OS: [e.g. macOS, iOS, Windows] 35 | - Browser: [e.g. Chrome, Safari] 36 | - Node version: [e.g. v16.0.0] 37 | - App version: [e.g. v1.0.0] 38 | 39 | ## Additional Information 40 | 41 | Any other information about the problem here. 42 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F4A1 Feature Request" 3 | about: Suggest an idea for this project 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | # Feature Request 10 | 11 | ## Describe the Feature 12 | 13 | A clear and concise description of what you want and what your use case is. 14 | 15 | ## Describe the Solution You'd Like 16 | 17 | A clear and concise description of what you want to happen. 18 | 19 | ## Describe Alternatives You've Considered 20 | 21 | A clear and concise description of any alternative solutions or features you've considered. 22 | 23 | ## Additional Information 24 | 25 | Any other information about the feature here. 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F914 Questions and Help" 3 | about: This issue tracker is not for questions. Please ask questions at https://stackoverflow.com/questions/tagged/react. 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | GitHub Issues are reserved for Bug reports and Feature requests. Support requests that are created as issues are likely to be closed. We want to make sure you are able to find the help you seek. Please take a look at the following resources. 10 | 11 | ## Coding Questions 12 | 13 | If you have a coding question related to React, it might be better suited for Stack Overflow. It's a great place to browse through frequent questions about using React, as well as ask for help with specific questions. 14 | 15 | https://stackoverflow.com/questions/tagged/react 16 | 17 | ## Support Forums 18 | 19 | There are many online forums which are a great place for discussion about best practices and application architecture. 20 | 21 | https://reactjs.org/community/support.html#popular-discussion-forums 22 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 12 | 13 | ## What 14 | 15 | What changes are being made? (e.g. feature, bug, docs, etc.) 16 | 17 | ## Why 18 | 19 | Why are these changes necessary? 20 | 21 | ## How 22 | 23 | How were these changes implemented? 24 | 25 | ## Checklist 26 | 27 | Have you done all of these things? 28 | 29 | 30 | 31 | 32 | - [ ] Documentation added 33 | - [ ] Tests 34 | - [ ] TypeScript definitions updated 35 | - [ ] Ready to be merged 36 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "21:00" 8 | open-pull-requests-limit: 10 9 | ignore: 10 | - dependency-name: stylelint-config-standard 11 | versions: 12 | - 22.0.0 13 | - dependency-name: core-js 14 | versions: 15 | - 3.10.2 16 | - dependency-name: "@types/helmet" 17 | versions: 18 | - 4.0.0 19 | - dependency-name: "@types/react-dom" 20 | versions: 21 | - 17.0.0 22 | - 17.0.1 23 | - 17.0.2 24 | - 17.0.3 25 | - dependency-name: eslint-config-prettier 26 | versions: 27 | - 7.2.0 28 | - 8.0.0 29 | - 8.1.0 30 | - 8.2.0 31 | - dependency-name: "@types/react" 32 | versions: 33 | - 17.0.0 34 | - 17.0.1 35 | - 17.0.2 36 | - 17.0.3 37 | - dependency-name: "@types/react-test-renderer" 38 | versions: 39 | - 17.0.0 40 | - 17.0.1 41 | - dependency-name: "@types/serialize-javascript" 42 | versions: 43 | - 5.0.0 44 | - dependency-name: webpack-bundle-analyzer 45 | versions: 46 | - 4.4.0 47 | - 4.4.1 48 | - dependency-name: fork-ts-checker-webpack-plugin 49 | versions: 50 | - 6.1.0 51 | - 6.1.1 52 | - 6.2.0 53 | - 6.2.1 54 | - dependency-name: mini-css-extract-plugin 55 | versions: 56 | - 1.3.5 57 | - 1.3.6 58 | - 1.3.7 59 | - 1.3.8 60 | - 1.3.9 61 | - 1.4.0 62 | - 1.4.1 63 | - dependency-name: webpack-dev-middleware 64 | versions: 65 | - 4.1.0 66 | - package-ecosystem: github-actions 67 | directory: "/" 68 | schedule: 69 | interval: daily 70 | time: "21:00" 71 | open-pull-requests-limit: 10 72 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - docker 8 | tags-ignore: 9 | - "**" 10 | pull_request: 11 | branches: 12 | - master 13 | - docker 14 | 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | 19 | strategy: 20 | matrix: 21 | node: [12, 14, 16] 22 | 23 | steps: 24 | - uses: actions/checkout@v3 25 | - name: Use Node.js ${{ matrix.node-version }} 26 | uses: actions/setup-node@v3 27 | with: 28 | node-version: ${{ matrix.node-version }} 29 | 30 | - name: Get yarn cache directory path 31 | id: yarn-cache-dir-path 32 | run: echo "::set-output name=dir::$(yarn cache dir)" 33 | - uses: actions/cache@v3 34 | id: yarn-cache 35 | with: 36 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 37 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 38 | restore-keys: | 39 | ${{ runner.os }}-yarn- 40 | 41 | - name: Install dependencies 42 | run: yarn install --frozen-lockfile 43 | - name: Run lint 44 | run: yarn lint 45 | - name: Run test 46 | run: yarn test:cov 47 | - name: Run build 48 | run: yarn build 49 | 50 | - name: Coveralls GitHub Action 51 | uses: coverallsapp/github-action@master 52 | with: 53 | github-token: ${{ secrets.GITHUB_TOKEN }} 54 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | schedule: 9 | # ┌───────────── minute (0 - 59) 10 | # │ ┌───────────── hour (0 - 23) 11 | # │ │ ┌───────────── day of the month (1 - 31) 12 | # │ │ │ ┌───────────── month (1 - 12 or JAN-DEC) 13 | # │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT) 14 | # │ │ │ │ │ 15 | # │ │ │ │ │ 16 | # │ │ │ │ │ 17 | # * * * * * 18 | - cron: "40 18 * * 1" 19 | 20 | jobs: 21 | CodeQL-Build: 22 | # CodeQL runs on ubuntu-latest, windows-latest, and macos-latest 23 | runs-on: ubuntu-latest 24 | 25 | permissions: 26 | # required for all workflows 27 | security-events: write 28 | 29 | # only required for workflows in private repositories 30 | actions: read 31 | contents: read 32 | 33 | steps: 34 | - name: Checkout repository 35 | uses: actions/checkout@v3 36 | 37 | # Initializes the CodeQL tools for scanning. 38 | - name: Initialize CodeQL 39 | uses: github/codeql-action/init@v2 40 | # Override language selection by uncommenting this and choosing your languages 41 | with: 42 | languages: javascript 43 | 44 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 45 | # If this step fails, then you should remove it and run the build manually (see below). 46 | - name: Autobuild 47 | uses: github/codeql-action/autobuild@v2 48 | 49 | # ℹ️ Command-line programs to run using the OS shell. 50 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 51 | 52 | # ✏️ If the Autobuild fails above, remove it and uncomment the following 53 | # three lines and modify them (or add more) to build your code if your 54 | # project uses a compiled language 55 | 56 | #- run: | 57 | # make bootstrap 58 | # make release 59 | 60 | - name: Perform CodeQL Analysis 61 | uses: github/codeql-action/analyze@v2 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules 3 | 4 | # Testing 5 | coverage 6 | 7 | # Production 8 | public/* 9 | !public/favicon.ico 10 | !public/logo192.png 11 | !public/logo512.png 12 | !public/manifest.json 13 | 14 | # Misc 15 | .DS_Store 16 | *.log 17 | 18 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn lint-staged 5 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn test 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Testing 2 | coverage 3 | 4 | # Production 5 | public/* 6 | !public/manifest.json 7 | 8 | # Misc 9 | *.log 10 | 11 | -------------------------------------------------------------------------------- /.stylelintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: ["stylelint-order"], 3 | extends: [ 4 | "stylelint-config-standard", 5 | "stylelint-config-sass-guidelines", 6 | "stylelint-config-prettier", 7 | ], 8 | ignoreFiles: ["public/assets/**/*.css", "coverage/**/*.css"], 9 | }; 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | This project adheres to [Semantic Versioning](http://semver.org). 4 | Every release, along with the migration instructions, is documented on the Github [Releases](https://github.com/wellyshen/react-cool-starter/releases) page. 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | hivoid19@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][mozilla coc]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][faq]. Translations are available 126 | at [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [homepage]: https://www.contributor-covenant.org 129 | [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html 130 | [mozilla coc]: https://github.com/mozilla/diversity 131 | [faq]: https://www.contributor-covenant.org/faq 132 | [translations]: https://www.contributor-covenant.org/translations 133 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to REACT COOL STARTER 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change. 4 | 5 | Please note we have a [code of conduct](CODE_OF_CONDUCT.md), please follow it in all your interactions with the project. 6 | 7 | > Working on your first Pull Request? You can learn how from [this free video series](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github). 8 | 9 | ## Pull Request Process 10 | 11 | 1. Fork the repository and create your branch from `master`. 12 | 2. Run `yarn` to install dependencies. 13 | 3. If you’ve fixed a bug or added code that should be tested. 14 | 4. Ensure the test suite passes by running `yarn test`. 15 | 5. Update the [README.md](README.md) with details of changes. 16 | 6. Make sure your code lints by running `yarn lint`. 17 | 18 | ## Development Workflow 19 | 20 | After cloning REACT COOL STARTER, run `yarn` to fetch its dependencies. Then, you can run [several commands](https://github.com/wellyshen/react-cool-starter#script-commands). 21 | 22 | ## Style Guide 23 | 24 | We use [ESLint](https://eslint.org), [StyleLint](https://stylelint.io) and [Prettier](https://prettier.io) for code style and formatting. Run `yarn lint` after making any changes to the code. Then, our linter will catch most issues that may exist in your code. 25 | 26 | However, there are still some styles that the linter cannot pick up. If you are unsure about something, looking at [Airbnb’s Style Guide](https://github.com/airbnb/javascript) will guide you in the right direction. 27 | 28 | ## License 29 | 30 | By contributing to REACT COOL STARTER, you agree that your contributions will be licensed under its MIT license. 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Welly Shen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # REACT COOL STARTER 2 | 3 | A simple but feature rich starter boilerplate for creating your own [universal](https://medium.com/@mjackson/universal-javascript-4761051b7ae9) app. It built on the top of [React](https://facebook.github.io/react), [Redux](https://github.com/reactjs/redux), [React Router](https://reacttraining.com/react-router) and [Express](https://expressjs.com). Includes all the hot stuff and modern web development tools such as [Redux Toolkit](https://redux-toolkit.js.org), [TypeScript](https://www.typescriptlang.org), [Webpack](https://webpack.js.org/), [Babel](https://babeljs.io), [PostCSS](https://github.com/postcss/postcss-loader), [React Refresh](https://github.com/facebook/react/tree/master/packages/react-refresh), [Jest](https://facebook.github.io/jest) and [React Testing Library](https://github.com/testing-library/react-testing-library). See the [**“Features”**](#features) section for other awesome features you can expect. 4 | 5 | > I will maintain the starter boilerplate and keep all of the technologies on trend. Welcome to join me if you want. Hope you guys love it 🤩 6 | 7 | [![build status](https://img.shields.io/github/workflow/status/wellyshen/react-cool-starter/CI?style=flat-square)](https://github.com/wellyshen/react-cool-starter/actions?query=workflow%3ACI) 8 | [![coverage status](https://img.shields.io/coveralls/github/wellyshen/react-cool-starter?style=flat-square)](https://coveralls.io/github/wellyshen/react-cool-starter?branch=master) 9 | [![dependencies status](https://img.shields.io/david/wellyshen/react-cool-starter?style=flat-square)](https://david-dm.org/wellyshen/react-cool-starter) 10 | [![devDependencies status](https://img.shields.io/david/dev/wellyshen/react-cool-starter?style=flat-square)](https://david-dm.org/wellyshen/react-cool-starter?type=dev) 11 | [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4?style=flat-square)](https://github.com/prettier/prettier) 12 | [![All Contributors](https://img.shields.io/badge/all_contributors-22-orange?style=flat-square)](#contributors-) 13 | [![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen?style=flat-square)](CONTRIBUTING.md) 14 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fwellyshen%2Freact-cool-starter)](https://twitter.com/intent/tweet?text=With%20@react-cool-starter,%20I%20can%20build%20my%20universal%20web%20app%20easily.%20Thanks,%20@Welly%20Shen%20🤩) 15 | 16 | ## Real Case Study 17 | 18 | > 💡 If you have built a production web app based on this starter, please open a PR to add it here. 19 | 20 | - [Spinny](https://www.spinny.com) is a fully inspected highest quality second hand cars with money-back guarantee. simple and transparent buying. 21 | - [BAM Music](https://www.bammusic.com) is a new generation of music platform for audio visual professionals, filmmakers and content producers. Upgrade your soundtrack with great music that emphasizes your story! 22 | - [Rendah Mag](https://www.rendahmag.com) is a music magazine which exists to bring exposure to an ever-growing community, focusing on the latest Halftime, Beats & Experimental news & releases. Congrats for the amazing product. 23 | - [DealDrop](https://www.dealdrop.com) is the best place to find verified coupon codes, deals, promos and offers for thousands of stores & brands you love. Never pay full price again. 24 | - [BECK Friends](https://www.beckfriends.com) is an international delivery service, which is built based on this starter boilerplate. Congrats for successful migrating to React. 25 | 26 | ## Features 27 | 28 | Really cool starter boilerplate with the most popular technologies: 29 | 30 | - [Universal](https://medium.com/@mjackson/universal-javascript-4761051b7ae9) rendering with async data fetching. 31 | - [React](https://facebook.github.io/react) as the view library. 32 | - [Redux](https://github.com/reactjs/redux) as the state management. 33 | - [Redux Toolkit](https://redux-toolkit.js.org) for efficient Redux development. 34 | - [React Router](https://reacttraining.com/react-router) as the router. 35 | - [Connected React Router](https://github.com/supasate/connected-react-router) to bind Redux with React Router. Refer to [document](https://github.com/supasate/connected-react-router/blob/master/FAQ.md#frequently-asked-questions) to see how it works. 36 | - [Express](https://expressjs.com) server. 37 | - [TypeScript](https://www.typescriptlang.org) as the static type checker for JavaScript. 38 | - [Webpack](https://webpack.js.org) for app bundling. 39 | - [Babel](https://babeljs.io) for transpile ES6+ to ES5. 40 | - [React Refresh](https://github.com/facebook/react/tree/master/packages/react-refresh) to fast refresh components without losing their state. 41 | - [nodemon](https://nodemon.io) to monitor for any changes in your Node.js application and automatically restart the server. 42 | - [axios](https://axios-http.com) as the Promise-based HTTP client for the browser and Node.js. 43 | - [react-helmet](https://github.com/nfl/react-helmet) to manage title, meta, styles and scripts tags on both server and client. 44 | - [loadable-component](https://github.com/smooth-code/loadable-components) to lazy load a component when needed. Reduce your bundle size without stress. 45 | - [Webpack Dev Middleware](https://github.com/webpack/webpack-dev-middleware) serves the files emitted from webpack over the Express server. 46 | - [Webpack Hot Middleware](https://github.com/glenjamin/webpack-hot-middleware) allows you to add hot reloading into the Express server. 47 | - [Webpack Bundle Analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer) creates a visualize size of webpack output files with an interactive zoomable treemap. 48 | - [helmet](https://github.com/helmetjs/helmet), [hpp](https://github.com/analog-nico/hpp), and [compression](https://github.com/expressjs/compression) for [server-Side security and performance](#server-side-security-and-performance). 49 | - [morgan](https://github.com/expressjs/morgan) the HTTP request logger for server side debugging. 50 | - [ESLint](http://eslint.org) to maintain a consistent TypeScript/JavaScript code style (with Airbnb configuration). 51 | - [stylelint](http://stylelint.io) to maintain a consistent CSS/SASS code style. 52 | - [Prettier](https://prettier.io) to format code and style. 53 | - CSS and SASS support with [PostCSS](https://github.com/postcss/postcss-loader) for advanced transformations (e.g. autoprefixer, cssnext etc.). [CSS modules](https://github.com/css-Modules/css-Modules) enabled. 54 | - Image (optimized/compressed by [Imagemin Webpack](https://github.com/webpack-contrib/image-minimizer-webpack-plugin)) and Font support. 55 | - Minimize JavaScript (by [terser-webpack-plugin](https://github.com/webpack-contrib/terser-webpack-plugin)) and CSS (by [css-minimizer-webpack-plugin](https://github.com/webpack-contrib/css-minimizer-webpack-plugin)) bundles for you. 56 | - Split vendor's libraries from client bundle. 57 | - No other view engines, just JavaScript based HTML rendering component. 58 | - Shared app configuration between development and production. 59 | - 404 error page and redirect handling. 60 | - Integrate [Jest](https://facebook.github.io/jest) with [React Testing Library](https://github.com/testing-library/react-testing-library) as the solution for writing unit tests with code coverage support. 61 | - [Yarn](https://yarnpkg.com/lang/en) as the package manager. 62 | 63 | ## Who's the Starter for? 64 | 65 | They're several React frameworks today, however this is a DIY oriented start-kit. It shows you how to build a universal web app from scratch and how to test it. If you're new to React or you want a ready-to-go solution, I'd recommend the following alternatives for you: 66 | 67 | - For client-side rendering, use [create-react-app](https://create-react-app.dev). 68 | - For server-side rendering, use [Next.js](https://nextjs.org). 69 | 70 | ## Requirements 71 | 72 | - [node](https://nodejs.org/en) >= 12.0 73 | - [npm](https://www.npmjs.com) >= 6.0 74 | 75 | ## Looking for Docker Image? 76 | 77 | You can find Docker support version on this [branch](https://github.com/wellyshen/react-cool-starter/tree/docker). 78 | 79 | ## Getting Started 80 | 81 | **1. You can start by cloning the repository on your local machine by running:** 82 | 83 | ```sh 84 | git clone https://github.com/wellyshen/react-cool-starter.git 85 | cd react-cool-starter 86 | ``` 87 | 88 | **2. Install all of the dependencies:** 89 | 90 | ```sh 91 | yarn 92 | ``` 93 | 94 | **3. Start to run it:** 95 | 96 | ```sh 97 | yarn build # Building bundle 98 | yarn start # Running production server 99 | ``` 100 | 101 | Now the app should be running at [http://localhost:8080](http://localhost:8080) 102 | 103 | > Note: You can change the port that you want from the `./src/config`. 104 | 105 | ## Script Commands 106 | 107 | I use [cross-env](https://github.com/kentcdodds/cross-env) to set and use environment variables across platforms. All of the scripts are listed as following: 108 | 109 | | `yarn 43 | 44 | 45 | ${extractor.getScriptTags()} 46 | ${head.script.toString()} 47 | 48 | 49 | `; 50 | 51 | // html-minifier configuration, refer to "https://github.com/kangax/html-minifier" for more configuration 52 | const minifyConfig = { 53 | collapseWhitespace: true, 54 | removeComments: true, 55 | trimCustomFragments: true, 56 | minifyCSS: true, 57 | minifyJS: true, 58 | minifyURLs: true, 59 | }; 60 | 61 | // Minify HTML in production 62 | return __DEV__ ? html : minify(html, minifyConfig); 63 | }; 64 | -------------------------------------------------------------------------------- /src/server/ssr.tsx: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { renderToString } from "react-dom/server"; 3 | import { StaticRouter } from "react-router-dom"; 4 | import { renderRoutes, matchRoutes } from "react-router-config"; 5 | import { Provider } from "react-redux"; 6 | import { ChunkExtractor } from "@loadable/server"; 7 | import { Helmet } from "react-helmet"; 8 | import chalk from "chalk"; 9 | import { Request, Response, NextFunction } from "express"; 10 | import { Action } from "@reduxjs/toolkit"; 11 | 12 | import createStore from "../store"; 13 | import renderHtml from "./renderHtml"; 14 | import routes from "../routes"; 15 | 16 | export default async ( 17 | req: Request, 18 | res: Response, 19 | next: NextFunction 20 | ): Promise => { 21 | const { store } = createStore({ url: req.url }); 22 | 23 | // The method for loading data from server-side 24 | const loadBranchData = (): Promise => { 25 | const branch = matchRoutes(routes, req.path); 26 | const promises = branch.map(({ route, match }) => { 27 | if (route.loadData) 28 | return Promise.all( 29 | route 30 | .loadData({ 31 | params: match.params, 32 | getState: store.getState, 33 | req, 34 | res, 35 | }) 36 | .map((item: Action) => store.dispatch(item)) 37 | ); 38 | 39 | return Promise.resolve(null); 40 | }); 41 | 42 | return Promise.all(promises); 43 | }; 44 | 45 | try { 46 | // Load data from server-side first 47 | await loadBranchData(); 48 | 49 | const statsFile = path.resolve(process.cwd(), "public/loadable-stats"); 50 | const extractor = new ChunkExtractor({ statsFile }); 51 | 52 | const staticContext: Record = {}; 53 | const App = extractor.collectChunks( 54 | 55 | {/* Setup React-Router server-side rendering */} 56 | 57 | {renderRoutes(routes)} 58 | 59 | 60 | ); 61 | 62 | const initialState = store.getState(); 63 | const htmlContent = renderToString(App); 64 | // head must be placed after "renderToString" 65 | // see: https://github.com/nfl/react-helmet#server-usage 66 | const head = Helmet.renderStatic(); 67 | 68 | // Check if the render result contains a redirect, if so we need to set 69 | // the specific status and redirect header and end the response 70 | if (staticContext.url) { 71 | res.status(301).setHeader("Location", staticContext.url); 72 | res.end(); 73 | 74 | return; 75 | } 76 | 77 | // Pass the route and initial state into html template, the "statusCode" comes from 78 | res 79 | .status(staticContext.statusCode === "404" ? 404 : 200) 80 | .send(renderHtml(head, extractor, htmlContent, initialState)); 81 | } catch (error) { 82 | res.status(404).send("Not Found :("); 83 | console.error(chalk.red(`==> 😭 Rendering routes error: ${error}`)); 84 | } 85 | 86 | next(); 87 | }; 88 | -------------------------------------------------------------------------------- /src/services/jsonPlaceholder.ts: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | import config from "../config"; 4 | 5 | export interface User { 6 | id: number; 7 | name: string; 8 | phone: string; 9 | email: string; 10 | website: string; 11 | } 12 | 13 | interface UserList { 14 | data?: User[]; 15 | error?: Error; 16 | } 17 | 18 | interface UserData { 19 | data?: User; 20 | error?: Error; 21 | } 22 | 23 | export const getUserList = async (): Promise => { 24 | try { 25 | const { data } = await axios.get(`${config.API_URL}/users`); 26 | return { data }; 27 | } catch (error) { 28 | return { error }; 29 | } 30 | }; 31 | 32 | export const getUserData = async (id: string): Promise => { 33 | try { 34 | const { data } = await axios.get(`${config.API_URL}/users/${id}`); 35 | return { data }; 36 | } catch (error) { 37 | return { error }; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /src/static/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/store/__tests__/userData.ts: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | import mockStore from "../../utils/mockStore"; 4 | import userData, { 5 | getRequesting, 6 | getSuccess, 7 | getFailure, 8 | fetchUserData, 9 | } from "../userData"; 10 | 11 | jest.mock("axios"); 12 | 13 | const mockData = { 14 | id: 1, 15 | name: "Welly", 16 | phone: "+886 0970...", 17 | email: "hivoid19@gmail.com", 18 | website: "https://wellyshen.com", 19 | }; 20 | const { id } = mockData; 21 | const mockError = "Oops! Something went wrong."; 22 | 23 | describe("userData reducer", () => { 24 | it("should handle initial state correctly", () => { 25 | // @ts-expect-error 26 | expect(userData(undefined, {})).toEqual({}); 27 | }); 28 | 29 | it("should handle requesting correctly", () => { 30 | expect( 31 | userData(undefined, { type: getRequesting.type, payload: id }) 32 | ).toEqual({ [id]: { readyStatus: "request" } }); 33 | }); 34 | 35 | it("should handle success correctly", () => { 36 | expect( 37 | userData(undefined, { 38 | type: getSuccess.type, 39 | payload: { id, item: mockData }, 40 | }) 41 | ).toEqual({ 42 | [id]: { readyStatus: "success", item: mockData }, 43 | }); 44 | }); 45 | 46 | it("should handle failure correctly", () => { 47 | expect( 48 | userData(undefined, { 49 | type: getFailure.type, 50 | payload: { id, error: mockError }, 51 | }) 52 | ).toEqual({ 53 | [id]: { readyStatus: "failure", error: mockError }, 54 | }); 55 | }); 56 | }); 57 | 58 | describe("userData action", () => { 59 | const strId = id.toString(); 60 | 61 | it("fetches user data successful", async () => { 62 | const { dispatch, getActions } = mockStore(); 63 | const expectedActions = [ 64 | { type: getRequesting.type, payload: strId }, 65 | { type: getSuccess.type, payload: { id: strId, item: mockData } }, 66 | ]; 67 | 68 | // @ts-expect-error 69 | axios.get.mockResolvedValue({ data: mockData }); 70 | 71 | await dispatch(fetchUserData(strId)); 72 | expect(getActions()).toEqual(expectedActions); 73 | }); 74 | 75 | it("fetches user data failed", async () => { 76 | const { dispatch, getActions } = mockStore(); 77 | const expectedActions = [ 78 | { type: getRequesting.type, payload: strId }, 79 | { type: getFailure.type, payload: { id: strId, error: mockError } }, 80 | ]; 81 | 82 | // @ts-expect-error 83 | axios.get.mockRejectedValue({ message: mockError }); 84 | 85 | await dispatch(fetchUserData(strId)); 86 | expect(getActions()).toEqual(expectedActions); 87 | }); 88 | }); 89 | -------------------------------------------------------------------------------- /src/store/__tests__/userList.ts: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | import mockStore from "../../utils/mockStore"; 4 | import userList, { 5 | initialState, 6 | getRequesting, 7 | getSuccess, 8 | getFailure, 9 | fetchUserList, 10 | } from "../userList"; 11 | 12 | jest.mock("axios"); 13 | 14 | const mockData = [ 15 | { 16 | id: 1, 17 | name: "Welly", 18 | phone: "+886 0970...", 19 | email: "hivoid19@gmail.com", 20 | website: "https://wellyshen.com", 21 | }, 22 | ]; 23 | const mockError = "Oops! Something went wrong."; 24 | 25 | describe("userList reducer", () => { 26 | it("should handle initial state", () => { 27 | // @ts-expect-error 28 | expect(userList(undefined, {})).toEqual(initialState); 29 | }); 30 | 31 | it("should handle requesting correctly", () => { 32 | expect(userList(undefined, { type: getRequesting.type })).toEqual({ 33 | readyStatus: "request", 34 | items: [], 35 | error: null, 36 | }); 37 | }); 38 | 39 | it("should handle success correctly", () => { 40 | expect( 41 | userList(undefined, { type: getSuccess.type, payload: mockData }) 42 | ).toEqual({ ...initialState, readyStatus: "success", items: mockData }); 43 | }); 44 | 45 | it("should handle failure correctly", () => { 46 | expect( 47 | userList(undefined, { type: getFailure.type, payload: mockError }) 48 | ).toEqual({ ...initialState, readyStatus: "failure", error: mockError }); 49 | }); 50 | }); 51 | 52 | describe("userList action", () => { 53 | it("fetches user list successful", async () => { 54 | const { dispatch, getActions } = mockStore(); 55 | const expectedActions = [ 56 | { type: getRequesting.type }, 57 | { type: getSuccess.type, payload: mockData }, 58 | ]; 59 | 60 | // @ts-expect-error 61 | axios.get.mockResolvedValue({ data: mockData }); 62 | 63 | await dispatch(fetchUserList()); 64 | expect(getActions()).toEqual(expectedActions); 65 | }); 66 | 67 | it("fetches user list failed", async () => { 68 | const { dispatch, getActions } = mockStore(); 69 | const expectedActions = [ 70 | { type: getRequesting.type }, 71 | { type: getFailure.type, payload: mockError }, 72 | ]; 73 | 74 | // @ts-expect-error 75 | axios.get.mockRejectedValue({ message: mockError }); 76 | 77 | await dispatch(fetchUserList()); 78 | expect(getActions()).toEqual(expectedActions); 79 | }); 80 | }); 81 | -------------------------------------------------------------------------------- /src/store/index.ts: -------------------------------------------------------------------------------- 1 | import { createMemoryHistory, createBrowserHistory } from "history"; 2 | import { Action, configureStore } from "@reduxjs/toolkit"; 3 | import { ThunkAction } from "redux-thunk"; 4 | import { routerMiddleware } from "connected-react-router"; 5 | 6 | import createRootReducer from "./rootReducer"; 7 | 8 | interface Arg { 9 | initialState?: typeof window.__INITIAL_STATE__; 10 | url?: string; 11 | } 12 | 13 | // Use inferred return type for making correctly Redux types 14 | // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types 15 | const createStore = ({ initialState, url }: Arg = {}) => { 16 | const history = __SERVER__ 17 | ? createMemoryHistory({ initialEntries: [url || "/"] }) 18 | : createBrowserHistory(); 19 | const store = configureStore({ 20 | preloadedState: initialState, 21 | reducer: createRootReducer(history), 22 | middleware: (getDefaultMiddleware) => [ 23 | // Included default middlewares: https://redux-toolkit.js.org/api/getDefaultMiddleware#included-default-middleware 24 | ...getDefaultMiddleware(), 25 | routerMiddleware(history), 26 | ], 27 | devTools: __DEV__, 28 | }); 29 | 30 | return { store, history }; 31 | }; 32 | 33 | const { store } = createStore(); 34 | 35 | export type AppState = ReturnType; 36 | 37 | export type AppDispatch = typeof store.dispatch; 38 | 39 | export type AppThunk = ThunkAction>; 40 | 41 | export default createStore; 42 | -------------------------------------------------------------------------------- /src/store/rootReducer.ts: -------------------------------------------------------------------------------- 1 | import { History } from "history"; 2 | import { connectRouter } from "connected-react-router"; 3 | 4 | import userList from "./userList"; 5 | import userData from "./userData"; 6 | 7 | // Use inferred return type for making correctly Redux types 8 | // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types 9 | export default (history: History) => ({ 10 | userList, 11 | userData, 12 | router: connectRouter(history) as any, 13 | // Register more reducers... 14 | }); 15 | -------------------------------------------------------------------------------- /src/store/userData.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction, createSlice } from "@reduxjs/toolkit"; 2 | 3 | import { User, getUserData } from "../services/jsonPlaceholder"; 4 | import { AppThunk, AppState } from "."; 5 | 6 | interface UserDate { 7 | [id: string]: { 8 | readyStatus: string; 9 | item?: User; 10 | error?: string; 11 | }; 12 | } 13 | 14 | interface Success { 15 | id: string; 16 | item: User; 17 | } 18 | 19 | interface Failure { 20 | id: string; 21 | error: string; 22 | } 23 | 24 | const userData = createSlice({ 25 | name: "userData", 26 | initialState: {} as UserDate, 27 | reducers: { 28 | getRequesting: (state, { payload }: PayloadAction) => { 29 | state[payload] = { readyStatus: "request" }; 30 | }, 31 | getSuccess: (state, { payload }: PayloadAction) => { 32 | state[payload.id] = { readyStatus: "success", item: payload.item }; 33 | }, 34 | getFailure: (state, { payload }: PayloadAction) => { 35 | state[payload.id] = { readyStatus: "failure", error: payload.error }; 36 | }, 37 | }, 38 | }); 39 | 40 | export default userData.reducer; 41 | export const { getRequesting, getSuccess, getFailure } = userData.actions; 42 | 43 | export const fetchUserData = 44 | (id: string): AppThunk => 45 | async (dispatch) => { 46 | dispatch(getRequesting(id)); 47 | 48 | const { error, data } = await getUserData(id); 49 | 50 | if (error) { 51 | dispatch(getFailure({ id, error: error.message })); 52 | } else { 53 | dispatch(getSuccess({ id, item: data as User })); 54 | } 55 | }; 56 | 57 | const shouldFetchUserData = (state: AppState, id: string) => 58 | state.userData[id]?.readyStatus !== "success"; 59 | 60 | export const fetchUserDataIfNeed = 61 | (id: string): AppThunk => 62 | (dispatch, getState) => { 63 | if (shouldFetchUserData(getState(), id)) return dispatch(fetchUserData(id)); 64 | 65 | return null; 66 | }; 67 | -------------------------------------------------------------------------------- /src/store/userList.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction, createSlice } from "@reduxjs/toolkit"; 2 | 3 | import { User, getUserList } from "../services/jsonPlaceholder"; 4 | import { AppThunk, AppState } from "."; 5 | 6 | interface UserList { 7 | readyStatus: string; 8 | items: User[]; 9 | error: string | null; 10 | } 11 | 12 | export const initialState: UserList = { 13 | readyStatus: "invalid", 14 | items: [], 15 | error: null, 16 | }; 17 | 18 | const userList = createSlice({ 19 | name: "userList", 20 | initialState, 21 | reducers: { 22 | getRequesting: (state: UserList) => { 23 | state.readyStatus = "request"; 24 | }, 25 | getSuccess: (state, { payload }: PayloadAction) => { 26 | state.readyStatus = "success"; 27 | state.items = payload; 28 | }, 29 | getFailure: (state, { payload }: PayloadAction) => { 30 | state.readyStatus = "failure"; 31 | state.error = payload; 32 | }, 33 | }, 34 | }); 35 | 36 | export default userList.reducer; 37 | export const { getRequesting, getSuccess, getFailure } = userList.actions; 38 | 39 | export const fetchUserList = (): AppThunk => async (dispatch) => { 40 | dispatch(getRequesting()); 41 | 42 | const { error, data } = await getUserList(); 43 | 44 | if (error) { 45 | dispatch(getFailure(error.message)); 46 | } else { 47 | dispatch(getSuccess(data as User[])); 48 | } 49 | }; 50 | 51 | const shouldFetchUserList = (state: AppState) => 52 | state.userList.readyStatus !== "success"; 53 | 54 | export const fetchUserListIfNeed = (): AppThunk => (dispatch, getState) => { 55 | if (shouldFetchUserList(getState())) return dispatch(fetchUserList()); 56 | 57 | return null; 58 | }; 59 | -------------------------------------------------------------------------------- /src/theme/variables.scss: -------------------------------------------------------------------------------- 1 | $color-dark-gray: #333; 2 | $color-white: #eee; 3 | -------------------------------------------------------------------------------- /src/types/index.d.ts: -------------------------------------------------------------------------------- 1 | declare const __CLIENT__: boolean; 2 | declare const __SERVER__: boolean; 3 | declare const __DEV__: boolean; 4 | 5 | declare module "*.svg"; 6 | declare module "*.gif"; 7 | declare module "*.png"; 8 | declare module "*.jpg"; 9 | declare module "*.jpeg"; 10 | declare module "*.webp"; 11 | declare module "*.css"; 12 | declare module "*.scss"; 13 | 14 | declare namespace NodeJS { 15 | interface Global { 16 | __CLIENT__: boolean; 17 | __SERVER__: boolean; 18 | __DEV__: boolean; 19 | $RefreshReg$: () => void; 20 | $RefreshSig$$: () => void; 21 | } 22 | } 23 | 24 | interface Window { 25 | __INITIAL_STATE__: Record; 26 | } 27 | -------------------------------------------------------------------------------- /src/utils/mockStore.tsx: -------------------------------------------------------------------------------- 1 | import { ReactNode } from "react"; 2 | import { Provider } from "react-redux"; 3 | import thunk from "redux-thunk"; 4 | import configurecreateMockStore from "redux-mock-store"; 5 | 6 | export default (obj = {}): Record => { 7 | const store = configurecreateMockStore([thunk])(obj); 8 | const originalDispatch = store.dispatch; 9 | store.dispatch = jest.fn(originalDispatch); 10 | 11 | const ProviderWithStore = ({ children }: { children: ReactNode }) => ( 12 | {children} 13 | ); 14 | 15 | return { ...store, ProviderWithStore }; 16 | }; 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "sourceMap": true, 4 | "target": "es5", 5 | "module": "commonjs", 6 | "lib": ["dom", "dom.iterable", "esnext"], 7 | "jsx": "react-jsx", 8 | // Specify module resolution strategy: "node" (Node.js) or "classic" (TypeScript pre-1.6) 9 | "moduleResolution": "node", 10 | // Enable all strict type-checking options. Recommended by TS 11 | "strict": true, 12 | // Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. 13 | // Implies "allowSyntheticDefaultImports". Recommended by TS 14 | "esModuleInterop": true, 15 | // Skip type checking of declaration files. Recommended by TS 16 | "skipLibCheck": true, 17 | // Disallow inconsistently-cased references to the same file. Recommended by TS 18 | "forceConsistentCasingInFileNames": true, 19 | // Do not emit outputs 20 | "noEmit": true, 21 | // Raise error on expressions and declarations with an implied "any" type 22 | "noImplicitAny": true, 23 | // Report errors on unused locals 24 | "noUnusedLocals": true, 25 | // Report errors on unused parameters 26 | "noUnusedParameters": true, 27 | // Report error when not all code paths in function return a value 28 | "noImplicitReturns": true, 29 | // Report errors for fallthrough cases in switch statement 30 | "noFallthroughCasesInSwitch": true 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /webpack/base.config.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import webpack, { 3 | Configuration, 4 | WebpackPluginInstance, 5 | RuleSetUseItem, 6 | } from "webpack"; 7 | import { WebpackManifestPlugin } from "webpack-manifest-plugin"; 8 | import TerserPlugin from "terser-webpack-plugin"; 9 | import MiniCssExtractPlugin from "mini-css-extract-plugin"; 10 | import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin"; 11 | import LoadablePlugin from "@loadable/webpack-plugin"; 12 | import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer"; 13 | 14 | export const isDev = process.env.NODE_ENV === "development"; 15 | 16 | const getStyleLoaders = (isWeb: boolean, isSass?: boolean) => { 17 | let loaders: RuleSetUseItem[] = [ 18 | { 19 | loader: "css-loader", 20 | options: { 21 | importLoaders: isSass ? 2 : 1, 22 | modules: { 23 | auto: true, 24 | localIdentName: isDev ? "[path][name]__[local]" : "[hash:base64]", 25 | exportOnlyLocals: !isWeb, 26 | }, 27 | }, 28 | }, 29 | { loader: "postcss-loader" }, 30 | ]; 31 | 32 | if (isWeb) loaders = [MiniCssExtractPlugin.loader, ...loaders]; 33 | 34 | if (isSass) loaders = [...loaders, { loader: "sass-loader" }]; 35 | 36 | return loaders; 37 | }; 38 | 39 | const getPlugins = (isWeb: boolean) => { 40 | let plugins = [ 41 | new webpack.ProgressPlugin(), 42 | new WebpackManifestPlugin({ 43 | fileName: path.resolve(process.cwd(), "public/webpack-assets.json"), 44 | filter: (file) => file.isInitial, 45 | }), 46 | new LoadablePlugin({ 47 | writeToDisk: true, 48 | filename: "../loadable-stats.json", 49 | }), 50 | // Setting global variables 51 | new webpack.DefinePlugin({ 52 | __CLIENT__: isWeb, 53 | __SERVER__: !isWeb, 54 | __DEV__: isDev, 55 | }), 56 | ]; 57 | 58 | if (isDev) 59 | plugins = [ 60 | ...plugins, 61 | // Runs TypeScript type checker on a separate process 62 | new ForkTsCheckerWebpackPlugin({ 63 | // (Required) Same as eslint command 64 | eslint: { files: "./src/**/*.{js,jsx,ts,tsx}" }, 65 | }), 66 | ]; 67 | 68 | if (!isDev) 69 | plugins = [ 70 | ...plugins, 71 | // Visualize size of webpack output files, see: https://github.com/webpack-contrib/webpack-bundle-analyzer 72 | new BundleAnalyzerPlugin({ 73 | analyzerMode: 74 | process.env.NODE_ENV === "analyze" ? "server" : "disabled", 75 | }), 76 | ]; 77 | 78 | return plugins; 79 | }; 80 | 81 | const config = (isWeb = false): Configuration => ({ 82 | mode: isDev ? "development" : "production", 83 | stats: "minimal", 84 | context: path.resolve(process.cwd()), 85 | output: { clean: true }, 86 | optimization: { 87 | minimizer: [ 88 | new TerserPlugin({ 89 | // See more options: https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions 90 | terserOptions: { compress: { drop_console: true } }, 91 | }), 92 | ], 93 | }, 94 | plugins: getPlugins(isWeb) as WebpackPluginInstance[], 95 | module: { 96 | rules: [ 97 | { 98 | test: /\.(t|j)sx?$/, 99 | exclude: /node_modules/, 100 | loader: "babel-loader", 101 | options: { 102 | caller: { target: isWeb ? "web" : "node" }, 103 | cacheDirectory: isDev, 104 | }, 105 | }, 106 | { 107 | test: /\.css$/, 108 | use: getStyleLoaders(isWeb), 109 | }, 110 | { 111 | test: /\.(scss|sass)$/, 112 | use: getStyleLoaders(isWeb, true), 113 | }, 114 | { 115 | test: /\.(woff2?|eot|ttf|otf)$/i, 116 | type: "asset", 117 | generator: { emit: isWeb }, 118 | }, 119 | { 120 | test: /\.(png|svg|jpe?g|gif)$/i, 121 | type: "asset", 122 | generator: { emit: isWeb }, 123 | }, 124 | ], 125 | }, 126 | resolve: { 127 | modules: ["src", "node_modules"], 128 | extensions: [".ts", ".tsx", ".js", ".jsx", ".json"], 129 | }, 130 | }); 131 | 132 | export default config; 133 | -------------------------------------------------------------------------------- /webpack/client.config.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import webpack, { Configuration } from "webpack"; 3 | import ReactRefreshWebpackPlugin from "@pmmmwh/react-refresh-webpack-plugin"; 4 | import MiniCssExtractPlugin from "mini-css-extract-plugin"; 5 | import CssMinimizerPlugin from "css-minimizer-webpack-plugin"; 6 | import CompressionPlugin from "compression-webpack-plugin"; 7 | import ImageMinimizerPlugin from "image-minimizer-webpack-plugin"; 8 | import merge from "webpack-merge"; 9 | 10 | import baseConfig, { isDev } from "./base.config"; 11 | 12 | const getPlugins = () => { 13 | let plugins = [ 14 | new MiniCssExtractPlugin({ 15 | // Don't use hash in development, we need the persistent for "renderHtml.ts" 16 | filename: isDev ? "[name].css" : "[name].[contenthash].css", 17 | chunkFilename: isDev ? "[id].css" : "[id].[contenthash].css", 18 | }), 19 | ]; 20 | 21 | if (isDev) 22 | plugins = [ 23 | ...plugins, 24 | new webpack.HotModuleReplacementPlugin(), 25 | new ReactRefreshWebpackPlugin({ overlay: { sockIntegration: "whm" } }), 26 | ]; 27 | 28 | if (!isDev) 29 | plugins = [ 30 | ...plugins, 31 | // Prepare compressed versions of assets to serve them with Content-Encoding 32 | new CompressionPlugin(), 33 | new ImageMinimizerPlugin({ 34 | // Lossless optimization with default option, feel free to experiment with options for better result for you 35 | // See https://github.com/webpack-contrib/image-minimizer-webpack-plugin#getting-started 36 | minimizerOptions: { 37 | plugins: [["gifsicle"], ["jpegtran"], ["optipng"], ["svgo"]], 38 | }, 39 | }), 40 | ]; 41 | 42 | return plugins; 43 | }; 44 | 45 | const config: Configuration = { 46 | devtool: isDev && "eval-cheap-source-map", 47 | entry: isDev 48 | ? ["webpack-hot-middleware/client?reload=true", "./src/client"] 49 | : "./src/client", 50 | output: { 51 | filename: isDev ? "[name].js" : "[name].[contenthash].js", 52 | chunkFilename: isDev ? "[id].js" : "[id].[contenthash].js", 53 | path: path.resolve(process.cwd(), "public/assets"), 54 | publicPath: "/assets/", 55 | }, 56 | optimization: { minimizer: [new CssMinimizerPlugin()] }, 57 | plugins: getPlugins(), 58 | }; 59 | 60 | export default merge(baseConfig(true), config); 61 | -------------------------------------------------------------------------------- /webpack/server.config.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import webpack, { Configuration } from "webpack"; 3 | import nodeExternals from "webpack-node-externals"; 4 | import merge from "webpack-merge"; 5 | 6 | import baseConfig, { isDev } from "./base.config"; 7 | 8 | const config: Configuration = { 9 | target: "node", 10 | devtool: isDev ? "inline-source-map" : "source-map", 11 | entry: "./src/server", 12 | output: { 13 | filename: "index.js", 14 | chunkFilename: "[id].js", 15 | path: path.resolve(process.cwd(), "public/server"), 16 | libraryTarget: "commonjs2", 17 | }, 18 | node: { __dirname: true, __filename: true }, 19 | externals: [ 20 | "@loadable/component", 21 | nodeExternals({ 22 | // Load non-javascript files with extensions, presumably via loaders 23 | allowlist: [/\.(?!(?:jsx?|json)$).{1,5}$/i], 24 | }), 25 | ], 26 | plugins: [ 27 | // Adding source map support to node.js (for stack traces) 28 | new webpack.BannerPlugin({ 29 | banner: 'require("source-map-support").install();', 30 | raw: true, 31 | }), 32 | ], 33 | }; 34 | 35 | export default merge(baseConfig(false), config); 36 | --------------------------------------------------------------------------------