Skip to content

Instantly share code, notes, and snippets.

@PabloPenia
Last active March 13, 2023 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PabloPenia/a6cafc628452cd3b3a8a8374c9d1e2f7 to your computer and use it in GitHub Desktop.
Save PabloPenia/a6cafc628452cd3b3a8a8374c9d1e2f7 to your computer and use it in GitHub Desktop.
Vite configuration for React-Typescript with Linter, formatter and custom paths
---
env:
browser: true
es2021: true
extends:
- plugin:react/recommended
- standard-with-typescript
- plugin:@typescript-eslint/recommended
- plugin:@typescript-eslint/recommended-requiring-type-checking
- plugin:import/recommended
- plugin:react/jsx-runtime
- plugin:jsx-a11y/recommended
- plugin:prettier/recommended
parser: '@typescript-eslint/parser'
parserOptions:
ecmaVersion: latest
sourceType: module
tsconfigRootDir: '.'
project:
- './tsconfig.json'
plugins:
- react
- react-hooks
- '@typescript-eslint'
- prettier
settings:
import/resolver:
typescript:
project: './tsconfig.json'
react:
version: detect
rules:
arrow-body-style:
- error
- as-needed
'@typescript-eslint/explicit-function-return-type': warn
'@typescript-eslint/triple-slash-reference': warn
'@typescript-eslint/no-explicit-any': warn
'@typescript-eslint/no-non-null-assertion': warn
'@typescript-eslint/no-unused-vars':
- error
- argsIgnorePattern: '^_'
varsIgnorePattern: '^_'
caughtErrorsIgnorePattern: '^_'
'@typescript-eslint/consistent-type-imports':
- error
- prefer: type-imports
react/button-has-type: error
react/no-array-index-key: warn
react/self-closing-comp:
- error
- component: true
html: true
react-hooks/rules-of-hooks: error
react-hooks/exhaustive-deps: warn
react/prop-types: warn
prettier/prettier:
- error
- jsxSingleQuote: true
singleQuote: true
semi: false
tabWidth: 2
trailingComma: all
bracketSameLine: false
useTabs: true
arrowParens: always
endOfLine: auto
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": [
"DOM",
"DOM.Iterable",
"ESNext"
],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noEmit": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"~/*": [
"src/*"
]
}
},
"include": [
"vite.config.ts",
"**/*.ts",
"**/*.tsx" ],
"exclude": [
"node_modules"
]
}

Starter framework for React with Vite and Typescript

This is a simple starter framework which includes linter, formatter and unit testing for React and Typescript using Vite. You can follow this steps to scaffold any app, but having in mind that this is my chosen workflow, I have customized some things, so please read commands before run to adapt to your own workflow.

Creating project with Vite

  • Run: yarn create vite my-app --template react-ts or yarn create vite and follow the prompts
  • Framework: React
  • Variant: Typescript
  • After the project is created run: cd my-app then: yarn or yarn install

Cleaning up

  • Run: find . \( -name "*.css" -o -name "*.svg" \) -type f This should return paths for 2 css files and 2 svg files, if thats so, run: find . \( -name "*.css" -o -name "*.svg" \) -type f -delete
  • Open index.html and remove references to deleted files, in vscode ctrl+F 'vite.svg'. Remove the entire line. Also edit the content on <title></title> for the title of your app.
  • Open src/App.tsx and remove all React scaffolding and imports:
export default function App() {
	return <div>Hello World!</div>
}
  • Edit src/Main.tsx, remove all content and replace it for following snippet:
import { createRoot } from 'react-dom/client'
import { StrictMode } from 'react'
import App from './App'

const rootEl = document.getElementById('root')

if (!rootEl) throw new Error('Failed to find the root element.')

const root = createRoot(rootEl as HTMLElement)

root.render(
	<StrictMode>
    		<App />
	</StrictMode>
)

Linting and formatting with Eslint and Prettier

This is an almost strict setup for linting and formatting. "Almost" because there are some "warns" that can be changed to "error". Prettier rules are embeded on eslint config, but you can also setup a .prettierrc file on root, or even at folder level (to change rules only in that folder).

On the root of your app run:

  • yarn add -D eslint @typescript-eslint/parser eslint-config-prettier eslint-import-resolver-typescript eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react-hooks prettier
  • then yarn create @eslint/config

and follow the prompts:

  • To: Check syntax, find problems, and enforce code style.
  • Imports: Javascript module (import/export).
  • Framework: React.
  • TypeScript: Yes.
  • Browser
  • Style: Use a popular style guide
  • Style Guide: Standard
  • File: YAML
  • Accept to install all dependencies with your package manager.

Edit: .eslintrc.yml

Adding aliases to src folder

  • yarn add -D vite-tsconfig-paths then update baseUrl and paths in tsconfig.json

Example with deeply nested components

Before: import MyComponent from '../../../../components/my-component.component.tsx After: import MyComponent from '~/components/my-component.component.tsx

Unit Testing with Vitest and Testing Library

  • Add Vitest, and Testing Library to dev dependencies: yarn add -D vitest @testing-library/react @testing-library/jest-dom
  • update vite.config.ts or create a new file vitest.config.ts. If vitest.config.ts is present will be have priority when running tests, otherwise, default vite.config.ts is used.
/// <reference types="vitest" />
/// <reference types="vite/client" />

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [react()],
	test: {
		globals: true,
		environment: 'jsdom',
		setupFiles: './src/test/setup.ts',
		// you might want to disable it, if you don't have tests that rely on CSS
		// since parsing CSS is slow
		css: false,
	},
})

Sources

Feel free to update to your needs or comment any improvement to these files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment