Add Vite to existing React project
Tags: react, vite
Published: 2021-05-05 07:10:26

Speed up your dev server with change build tool from webpack to Vite.

## Steps

Install packages.

```bash
npm i -D vite @vitejs/plugin-react-refresh
```

Create a vite config file:  `vite.config.ts`

```typescript
// vite.config.ts
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'

export default defineConfig({
  plugins: [reactRefresh()]
})
```

Edit `package.json`

```json
// package.json
{
  "scripts": {
    "start": "vite",
    "build": "vite build"
    // if you need to run eslint and tsc
    "build": "eslint src && tsc && vite build",
  },
}
```

Move `index.html` from `/public` to your project root, remove all `%PUBLIC_URL%`, and add a `<script>` tag to referehce `/src/index.tsx`, or `/src/index.jsx` if is JavaScript project.

```html
<!-- index.tsx or index.jsx -->

<!-- before -->
- <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
- <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
- <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

<!-- after -->
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="apple-touch-icon" href="/logo192.png" />
+ <link rel="manifest" href="/manifest.json" />

  <div id="root"></div>
+ <script type="module" src="/src/index.tsx"></script>
```

That is all, run `npn run start` and check if anything is ok.

# Other settings

If your project have those dependency, than you need to do more setup for Vite.



## SCSS

Just replace `node-sass` package with `sass`.

```bash
npm i -D sass
npm un node-sass
```



## CSS module localsConvention

Reference css class that is naming with dahs-case  `.css-class-name { ... }` with camelCase  `className={styles.cssClassName}` in code. 

```typescript
// vite.config.ts
export default defineConfig({
  css: { modules: { localsConvention: 'camelCase' } },
});
```



## Path alias

Shorten your import statements. for example:

```typescript
// SomeComponent.tsx
- import { ApiService } from '../../../services/api-serivce';
+ import { ApiService } from '@serivces/api-serivce';
```

### Setup

```json
// tsconfig.json or jsconfig.json
{
  "extends": "./tsconfig.paths.json", // or "./jsconfig.paths.json"
}
```

```json
// tsconfig.paths.json or jsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@services/*": ["src/services/*"],
    }
  }
}
```

Read `tsconfig.paths.json` from `vite.config.ts`

```typescript
// vite.config.ts
import path from 'path';

import { Alias, defineConfig } from 'vite';

import * as tsconfig from './tsconfig.paths.json';

function readAliasFromTsConfig(): Alias[] {
  const pathReplaceRegex = new RegExp(/\/\*$/, '');
  return Object.entries(tsconfig.compilerOptions.paths).reduce(
    (aliases, [fromPaths, toPaths]) => {
      const find = fromPaths.replace(pathReplaceRegex, '');
      const toPath = toPaths[0].replace(pathReplaceRegex, '');
      const replacement = path.resolve(__dirname, toPath);
      aliases.push({ find, replacement });
      return aliases;
    },
    [] as Alias[],
  );
}

export default defineConfig({
  resolve: {
    alias: readAliasFromTsConfig(),
  },
});
```



## Proxy

```typescript
// vite.config.ts
import reactRefresh from '@vitejs/plugin-react-refresh';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [reactRefresh()],
  server: {
    proxy: {
      '/api': 'https://your-api-server.com',
    },
  },
});
```



## References

[Issue comment of Vite creator](https://github.com/vitejs/vite/issues/1652#issuecomment-765875146)

[Commit of my side project](https://github.com/huybn5776/liu-online-ime/commit/cfe2ec8a0d5a905788a96774fdb536ef89edd054)

[Comparing the New Generation of Build Tools](https://css-tricks.com/comparing-the-new-generation-of-build-tools/#vite)