前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vite 创建React中遇到的坑

vite 创建React中遇到的坑

作者头像
用户9914333
发布2022-12-14 18:00:24
2.6K0
发布2022-12-14 18:00:24
举报
文章被收录于专栏:bug收集bug收集

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:

代码语言:javascript
复制
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文件

代码语言:javascript
复制
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 函数从文件系统导入多个模块

代码:

代码语言:javascript
复制
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导入的组件


苟有恒 , 何必三更眠五更起

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-11-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 bug收集 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档