webpack 迁移 vite 问题记录

321 阅读3分钟

webpack迁移到vite的一些问题点记录

1、更改index.html文件

public目录下的index.html文件移动到项目根目录, 与 /public 中的 index.html 主要不同的地方有两点:一是要以 type="module" 形式导入脚本,二是在引入 /public 路径下资源的时候不需要加前缀。

// <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="icon" href="/favicon.ico" />

<script type="module" src="/src/index.tsx"></script>

2、 配置 alias

迁移过程中可能会遇到这样的报错

图片.png 提示 Vite 无法找到 ~antd/dist/antd.less 文件。可能是因为 vite解析不了~ 符号导致的,在vite.config文件里面配置alise解决。

alias: [
        {
          find: /^~/,
          replacement: '',
        },
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src'),
        },
      ],

3、以 React 组件的形式导入 svg

以react组件形式导入svg会报错

图片.png

CRA 使用了svgr 来支持将 svg 以 react 组件形式导入,在 vite 需要插件vite-plugin-svgr来支持以React 组件的形式导入 svg

import svgr from 'vite-plugin-svgr'
plugins: [ svgr()],

4、styled-component/macro 产生的报错

图片.png

很多cra项目中使用了styled-component/macro ,但是他们都依赖 babel-macro 插件,因为 cra 自带 babel-macro 插件, styled-component/macro 可以被正常解析,但是在vite中没有集成babel-macro 这种插件,配置vite-plugin-babel-macros解决这个报错。

import macrosPlugin from 'vite-plugin-babel-macros'
plugins: [ macrosPlugin()],

5、启用 javascriptEnabled 选项

图片.png 这个报错通常是由于 Vite 在解析 Less 文件时没有启用 javascriptEnabled 选项引起的。解决方法是在vite.config文件添加一个针对 Less 文件的处理规则,并在 css.preprocessorOptions.less 中启用 javascriptEnabled

如果想要修改Ant Design 的主题色或其他默认样式,可以在modifyVars中进行修改

css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          modifyVars: { '@primary-color': '#01ab5d' },//修改ant-design主题色
        },
      },
    },

6、vite-plugin-node-polyfills引入 polyfills

polyfill是一种在旧版本浏览器中实现新的 JavaScript 特性的方法。它可以填充浏览器不支持的 API

在 Node.js 环境中,有一些常用的全局变量和模块(如 process 等)在浏览器中是不可用的,如果代码中使用了这些 Node.js 独有的特性会导致项目报错。vite-plugin-node-polyfills 插件可以帮助自动引入这些 polyfills,让代码可以在浏览器中正常运行。

import { nodePolyfills } from 'vite-plugin-node-polyfills'
plugins: [nodePolyfills()],

7、Failed to resolve import "react/jsx-dev-runtime"

图片.png 因为当前项目的react版本太低导致的,在vite.config文件中配置以下代码解决:

import react from '@vitejs/plugin-react'
plugins: [
      react(
        {
          jsxRuntime: 'classic', //指定 React 的 JSX 运行时为`classic`模式。
        }
      ),
    ],

解析JSX代码有两种模式:classic 模式和 automatic 模式,参考这边文章

classic 模式是在 React 16 版本之前使用的默认模式; automatic 模式是在 React 17 版本中引入的新模式。 由于@vitejs/plugin-react这个插件默认使用automatic模式,而项目的react16 版本太低,导致产生这个报错,加入这句代码jsxRuntime: 'classic', 指定使用classic模式解析JSX代码。

8、rquire is not defined

图片.png

vite 使用 ESM作为默认模块系统,而不是 CommonJS 模块系统,不支持使用 require 来导入模块。 使用 require 进行模块导入的代码,可以使用 import 进行迁移。

// CommonJS 模式
// const QRCode = require('qrcode-react')

// ESM 模式
import QRCode from 'qrcode-react'

9、类型ImportMeta上不存在属性env

图片.png

缺少TS类型提示,需要提供 Vite 客户端库的类型声明,有两种方式提供:

  • 添加一个 d.ts 声明文件:
/// <reference types="vite/client" />
  • 或则将 vite/client 添加到 tsconfig.json 中的 compilerOptions.types 下:
{ "compilerOptions": { "types": ["vite/client"] } }