美文网首页想法简友广场读书
使用Vite构建Vue踩坑记录

使用Vite构建Vue踩坑记录

作者: 技术的游戏 | 来源:发表于2022-10-20 14:49 被阅读0次

    今日九月二十五,星期四。宜嫁娶订盟,忌斋醮安门。

    一、解决npm下载慢或者下载不了的问题

    // 设置淘宝镜像的地址
    
    npm configsetregistry http://registry.npm.taobao.org
    
    // 查看当前的下载地址
    
    npm configgetregistry
    

    二、Vite跨域配置

    在Vite官网有这样一段配置可以设置跨域的地址

    export default defineConfig({
      server: {
        proxy: {
          // 字符串简写写法
          '/foo':'http://localhost:4567',
          // 选项写法
          '/api': {
            target:'http://jsonplaceholder.typicode.com',
          changeOrigin:true,
          rewrite:(path) =>path.replace(/^\/api/,'')
          },
          ...    
        }  
      }
    })
    

    Vite官网解决方案链接:
    https://cn.vitejs.dev/config/server-options.html#server-proxy

    三、Vite打包只有runtime模式

    在开发阶段Vite的打包速度远大于Webpack,这是因为Webpack先打包再启动开发服务器。而Vite直接启动开发服务器,然后按需编译依赖文件。

    new Vue({    el:'#app',    router,    components: { App },    template:'<App/>'  })
    

    需要修改为

    new Vue({    el:'#app',    router,    components: { App },    render:(h)=>h(App)  })
    

    四、使用require()动态导入图片报错和解决方法

    这是因为Vite使用Typescript开发,但是Typescript不支持require,最后会出require is not defined这样的错误。

    returnrequire("../../assets/img/user.png");
    

    需要修改为

    returnnewURL("../../assets/img/user.png",import.meta.url);
    

    Vite官网解决方案链接:
    https://cn.vitejs.dev/guide/assets.html

    五、加载JSON文件,解析JSON失败

    出现failed to parse json这样问题的时候,是因为JSON文件需要完整的原数据格式,不需要类似的注释、export、包装等。

    module.exports= [  {"hello":"world"}  ]
    

    需要修改为

    [  {"hello":"world"}  ]
    

    相关文章

      网友评论

        本文标题:使用Vite构建Vue踩坑记录

        本文链接:https://www.haomeiwen.com/subject/aceuzrtx.html