Vite2 + React + Antd 踩坑指南

process is not defined

報錯:

Uncaught ReferenceError: process is not defined

解決方案:

// 使用 import.meta.env 替換 process.env
process.env --> import.meta.env
# .env

# 字段名必須以 VITE_ 開頭,否則不會暴露到 import.meta.env 中
VITE_APP_VERSION = "1.0.0"

Property 'env' does not exist on type 'ImportMeta'

報錯:

Property 'env' does not exist on type 'ImportMeta'

解決方案:

# tsconfig.json

{
  "compilerOptions": {
    "types": ["vite/client"],
    ...
  }
}       

_interopRequireDefault is not a function

報錯:

Uncaught TypeError: _interopRequireDefault is not a function
    at Form.js:24
    at chunk.2VCUNPV2.js?v=9e816b32:4
    at dep:antd_lib_form_Form:1

解決方案:

// useForm 從錯誤的包導入,導致報錯
// import { useForm } from 'antd/lib/form/Form'
// import { useForm } from 'antd/es/form/Form'
// const [form] = useForm()

// 通過 Form 調用,不會出現導包錯誤的問題
import { Form } from 'antd'
const [form] = Form.useForm()

global is not defined

報錯:

Uncaught ReferenceError: global is not defined
    at setImmediate.js:15
    at chunk.2VCUNPV2.js?v=e11687d4:4
    at editOnBeforeInput.js:25
    at chunk.2VCUNPV2.js?v=e11687d4:4
    at DraftEditorEditHandler.js:16
    at chunk.2VCUNPV2.js?v=e11687d4:4
    at DraftEditor.react.js:32
    at chunk.2VCUNPV2.js?v=e11687d4:4
    at Draft.js:24
    at chunk.2VCUNPV2.js?v=e11687d4:4

解決方案:

<!-- index.html -->

<html>
  ...
  <body>
    <script>
      global = globalThis
    </script>
    ...
  </body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章