DEV Community

Huybn
Huybn

Posted on • Edited on

Add Vite to existing React project

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

Steps

Install packages.

npm i -D vite @vitejs/plugin-react-refresh
Enter fullscreen mode Exit fullscreen mode

Create a vite config file: vite.config.ts

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

export default defineConfig({
  plugins: [reactRefresh()]
})
Enter fullscreen mode Exit fullscreen mode

Edit package.json

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

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.

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

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.

npm i -D sass
npm un node-sass
Enter fullscreen mode Exit fullscreen mode

CSS module localsConvention

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

// vite.config.ts
export default defineConfig({
  css: { modules: { localsConvention: 'camelCase' } },
});
Enter fullscreen mode Exit fullscreen mode

Path alias

Shorten your import statements. for example:

// SomeComponent.tsx
- import { ApiService } from '../../../services/api-serivce';
+ import { ApiService } from '@serivces/api-serivce';
Enter fullscreen mode Exit fullscreen mode

Setup

// tsconfig.json or jsconfig.json
{
  "extends": "./tsconfig.paths.json", // or "./jsconfig.paths.json"
}
Enter fullscreen mode Exit fullscreen mode
// tsconfig.paths.json or jsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@services/*": ["src/services/*"],
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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

// 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(),
  },
});
Enter fullscreen mode Exit fullscreen mode

Proxy

// 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',
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

References

Issue comment of Vite creator

Commit of my side project

Comparing the New Generation of Build Tools

Top comments (3)

Collapse
 
aagamdoshi profile image
Aagam Doshi

Can you please help me to have a proper working application using lib

Below is my current vite config.js with build with lib configuration, it worked properly using your current build config

vite.config.js

`/* eslint-disable import/no-extraneous-dependencies */

import reactRefresh from '@vitejs/plugin-react-refresh';
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({
build: {
lib: {
entry: path.resolve(__dirname, "src/main.tsx"),
name: "Aagam",
},
rollupOptions: {
external: ["react"],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
react: 'React',
},
},
},
minify: true,
sourcemap: false,
},
plugins: [reactRefresh()],
resolve: {
alias: readAliasFromTsConfig(),
},
css: {
modules: { localsConvention: 'camelCase' },
preprocessorOptions: {
scss: {
additionalData: $injectedColor: orange;
}
}
}
});

`

package.json

"name": "@cimpress-technology/reporting-ui-component",
"version": "1.0.0",
"files": [
"dist"
],
"typings": "./dist/reporting-ui-component.d.ts",
"main": "./dist/reporting-ui-component.umd.js",
"module": "./dist/reporting-ui-component.es.js",
"scripts": {
"dev": "vite",
"build": "tsc && vite build && tsc -P tsconfig.dts.json",
"serve": "vite preview",
"start": "npm run dev",
"lint:fix": "eslint src --ext .jsx,.js,.ts,.tsx --quiet --fix",
"lint:format": "prettier --loglevel warn --write \"./*/.{js,jsx,ts,tsx,css,md,json}\" ",
"lint": "yarn lint:format && yarn lint:fix ",
"type-check": "tsc",
"lint-staged": "npx lint-staged -r",
"validate": "npm run style",
"validate-commit": "npm run lint-staged",
"style": "npx -q eslint src --ext .ts,.tsx --fix"
}

tsconfig.dts.json

{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"declaration": true,
"declarationDir": "dist",
"emitDeclarationOnly": true
},
"include": ["src"]
}
It would be great if you could provide some solution to it?
I am getting error on running above config

Error: lib folder is generated properly but when loaded on localhost it says
Cannot GET/

Stackoverflow : stackoverflow.com/questions/677234...

Github Issue : github.com/huybn5776/liu-online-im...

Collapse
 
huybn5776 profile image
Huybn

any message in command console? Usually, if you see "Cannot GET/" then you will also see another error message in console that run dev server.

Collapse
 
clericcoder profile image
Abdulsalaam Noibi

Wow,Thanks I really learn a lot