Using vite development in webpack + React project

Recently, when I was writing a large-scale project, I found that the compilation process was very slow and long. In order to improve the development experience and learn vite at the same time, I tried to use vite to start a development service in the webpack + React project (the speed of vite is not here. I’ve said more, everyone who understands it), I finally succeeded after working for an afternoon. Don’t talk nonsense, just start the whole thing.

If you use typescript in your project, then you only need four steps:

1. Installation dependencies

yarn add -D vite @vitejs/plugin-react

2. Add a configuration file

Add a vite.config.js file in the project root directory and write

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
 
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: { // 配置别名
      '@': resolve('src'),
    },
  },
});
复制代码

View more vite configurations

3. Add the entry file

Put a copy of index.html in public in the project root directory and write

<div id="root"></div>
<script>
  window.process = {
    env: {
      REACT_APP_ENV'test'
    }
  }
</script>
<script type="module" src="/src/index.tsx"></script>
复制代码

Fourth, add scripts command

add dev command in package.json

"scripts": {
    "dev""vite"
}
复制代码

After configuring the above four steps, my webpack + React + typescript project can already use vite to start development services through yarn dev.

But when I used it with confidence in another old project that did not use typescript, I found a lot of errors, let's solve them one by one:

Error 1. The jsx syntax is not recognized

This is because vite will only parse jsx syntax for .ts .tsx .jsx files by default, so if jsx is written in the js file in the project, vite will report an error

solution

When I saw this error, I subconsciously thought of changing the js file to jsx, but after looking at the hundreds of js files in the project, I was silent, there must be a better solution, and finally I found a comparison in vite's issues A good solution ( original ), add the following configuration to vite.config.js so that esbuild can recognize jsx in js files when precompiling

optimizeDeps: {
    esbuildOptions: {
      plugins: [
        {
          name'load-js-files-as-jsx',
          setup(build) {
            build.onLoad({ filter: /src/.*.js$/ }, async args => ({
              loader'jsx',
              contents: await fs.readFile(args.path, 'utf8'),
            }));
          },
        },
      ],
    },
 },
复制代码

But I tried it and it didn't work well in my project, and finally solved the problem with a babel plugin: @babel/plugin-transform-react-jsx

plugins: [
    react({
      babel: {
        plugins: ['@babel/plugin-transform-react-jsx'],
      },
    }),
],
复制代码

Error two, postcss 8 version problem

postcss版本冲突原因(vite中引用了postcss 8 版本)

解决方案

在package.json中resolution中指定一下pastcss版本就好了

"resolutions": {
    "postcss""^8.4.6",
},
复制代码

报错三:Inline JavaScript is not enabled

解决方案

在vite.config.js中添加css配置

css: {
  preprocessorOptions: {
    less: {
      javascriptEnabledtrue,
    },
  },
},
复制代码

报错四:require is not defined

项目中使用了require,vite不支持

解决方案

1、安装 @originjs/vite-plugin-commonjs 插件

yarn add -D @originjs/vite-plugin-commonjs

2、vite.config.js 中使用插件

import { viteCommonjs } from '@originjs/vite-plugin-commonjs';
 
...

plugins: [
  react({
    babel: {
      plugins: ['@babel/plugin-transform-react-jsx'],
    },
  }),
  viteCommonjs(),
],
复制代码

报错五:vite不支持  require.context 写法

// const files = require.context('./models', false, /\.js$/);

解决方案

这里使用 import.meta.globEager() 代替 require.context

const files = import.meta.globEager('./models/*.js');

以上就是我今天在 webpack + react 项目中体验 vite 的全过程,有不足的地方欢迎评论区讨论,在线接受批评。

Guess you like

Origin juejin.im/post/7078969057520648205