vite 创建React中遇到的坑
bug收集:专门解决与收集bug的网站
网址:www.bugshouji.com
最近,使用vite创建react项目,
将遇到的一些问题总结了一下,分享给大家
问题1:vite中运行无法使用外部ip访问
解决方法:
方法一:
运行npx vite --host 0.0.0.0
npm run dev --host
方法二:
在vite.config.js中增加配置server:
export default defineConfig({
plugins: [react()],
server:{
host:"0.0.0.0"
}
})
问题2:不会对 js 做 jsx 的语法转换
报错:[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
解决方案:
1. 安装 @babel/plugin-transform-react-jsx 的插件 npm i @babel/plugin-transform-react-jsx 2. 再配置 vite.config.js文件
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react({
babel: {
plugins: ['@babel/plugin-transform-react-jsx'],
},
})],
server: {
host: "0.0.0.0"
}
})
问题3:Uncaught ReferenceError: React is not defined
解决方案:只需要在提示错误的文件中引入React即可 代码如下: import React,{ useState } from 'react'
问题4:使用@loadable/component动态路由的实现方法
Vite 支持使用特殊的 import.meta.glob 函数从文件系统导入多个模块
代码:
import React from 'react';
import loadable from '@loadable/component'
const modules = import.meta.glob('./*/*.js')
function bindRouter(list) {
let arr = [];
list.map((item) => { const path = `./${item.componentPath}.js`
const ComponentNode = loadable(async () => {
return modules[path]();
});
if (item.menuChilds && item.menuChilds.length > 0) {
if (item.isContainChildren) {
arr.push({
path: item.pathRoute,
element: <ComponentNode />,
children: [...bindRouter(item.menuChilds)]
})
} else {
arr.push({
path: item.pathRoute,
//element:<ComponentNode/>
children: [...bindRouter(item.menuChilds)]
})
}
} else {
arr.push({
path: item.pathRoute,
element: <ComponentNode />
})
}
})
return arr;
}
modules 打印效果如下:
modules为一个对象,对应键名为路径名,对应值为一个函数返回import导入的组件
苟有恒 , 何必三更眠五更起
相关文章
- Ansible PlayBook语法
- Ansible 通过Playbook部署LAMP
- InnoDB的锁(Locking)
- Ansible 通过PlayBook部署Zabbix
- 一次死锁(Dead Lock)分析
- 【matplotlib】3-绘制统计图形
- 融资
- 共享文件夹
- Docker Registry
- 编译LAMP部署动态网站环境
- 如何在本地Fabric release-2.2上快速make all成功
- 编译LNMP部署动态网站环境
- Odoo 基于Win10搭建基于Win10搭建odoo14开发环境搭建
- certutil 命令配合PS反弹后门
- nacos v2.2 k8s部署启动报错:nacos server did not start because dumpservice bean construction failure. errMs
- 使用 openPDF 创建带目录的文档时候, 使用如下方式, 可以保证目录页码准确
- Web前端开发HTML笔记
- Web前端开发CSS笔记
- 花个几分钟,带你再了解一下Java注解
- 数字化供应链|B2B供应链协同可视化如何应用全程业务化管理