vue2切react技术栈之(2)-开始编程前的处理

118 阅读1分钟

一、上来先把不要的代码删掉

1.1 去掉“StrictMode”模式

# src\main.tsx


// import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  // <React.StrictMode>
    <App />
  // </React.StrictMode>,
)

为什么?

“StrictMode”模式会导致effect和函数组件render每次执行2次。

image.png

例如以上代码的执行结果:(就问一句看着难不难受~)

image.png

1.2 清空src\App.tsx的代码

function App() {
  return (
    <>
      我是App
    </>
  )
}

export default App

删掉不用的代码

  • 删掉src\assets\react.svg
  • 删掉src\App.css
  • 删掉src\index.css

页面结果如下:

image.png

工程干净了

image.png

二、开始安装其他依赖

2.1 安装开发环境依赖

pnpm add @types/node -D
pnpm add unplugin-auto-import -D
pnpm add sass -D

配置开发环境

新建build/utils、build/plugins文件夹

// plugins/index.ts

import { startReactPlugin } from './react';
import { UnPlugin } from './unplugin';

export const StartVitePlugins = () => {
  return [startReactPlugin(), UnPlugin()];
};
// plugins/react.ts

import react from '@vitejs/plugin-react-refresh';
export const startReactPlugin = () => {
  return react();
};
// plugins/unplugin.ts

import AutoImport from 'unplugin-auto-import/vite';
import { getSrcPath } from '../utils';

export const UnPlugin = () => {
  const srcPath = getSrcPath();
  return AutoImport({
    imports: ['react'],
    dirs: [`${srcPath}/hooks/**`], // 这里你可以新建你得hooks文件夹,内部抛出各种hook
    dts: 'typings/auto-imports.d.ts',
  });
};
// plugins/utils/index.ts

import { resolve } from 'path';
/**
 * 获取当前的src的路径
 * @returns
 */
export const getSrcPath = () => {
  return resolve(getRootPath(), 'src');
};

/**
 * 获取当前工程的根的路径
 * @returns
 */
export const getRootPath = () => {
  return process.cwd();
};

修改vite.config.ts

// vite.config.ts

import { defineConfig } from 'vite';
import { getSrcPath, getRootPath } from './build/utils';
import { StartVitePlugins } from './build/plugins';

export default defineConfig(() => {
  const srcPath = getSrcPath();
  const rootPath = getRootPath();
  return {
    plugins: StartVitePlugins(),
    resolve: {
      alias: {
        '@': srcPath,
        '~': rootPath,
      },
    },
  };
});