解决Vue打包后单机index.html页面无内容(比如用的是本地资源)

解决vue-cli打包后html文件引用本地js文件(里面是json数据)失效,打开空白问题

我的项目没有使用webpack 和vite工具进行打包 纯原始打包

一篇解决问题的博客,最近打包vue项目的时候出现html打开页面显示空白,看网络上这种解决方法需要付费。
首先要说明的问题使用vue项目执行run npm build,然后发现打包后的html文件,打开后是空白的l配置路径一定是有问题的。

直接上干货

先看路由 路由的话改成hash模型 ,使用import 引入createWebHashHistory 模块

import { createRouter, createWebHistory ,createWebHashHistory } from 'vue-router';
import Home from '../components/HelloWorld.vue';
import AboutAa from '../components/AboutA.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/AboutA',
    name: 'AboutA',
    component: AboutAa,

  }
];

const router = createRouter({
  // history: createWebHistory(),
  history: createWebHashHistory (),
  routes
});

export default router;

vue.config.js 中进行配置操作

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,	// 只需要在原有的语句的基础上加上这一句
  publicPath: './',
  /* 输出文件目录:在npm run build时,生成文件的目录名称 */
  outputDir: './dist',
  /* 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录 */
  assetsDir: "static",
  /* 是否在构建生产包时生成 sourceMap 文件,false将提高构建速度 */
  productionSourceMap: false,
  /* 默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存,你可以通过将这个选项设为 false 来关闭文件名哈希。(false的时候就是让原来的文件名不改变) */
  devServer: {
    /* 自动打开浏览器 */
    open: true,
    // proxy: {
    //   '/api': {
    //     target: 'http://localhost:3000', // 这里是你本地服务器的地址
    //     changeOrigin: true,
    //     pathRewrite: {
    //       '^/api': '',
    //     },
    //   },
    // }
  },

})

把文件进行 赋值导出 

 

在assets中新建js文件夹存放data.js文件,在相应的组件中进行解构 引入

 在页面中引入获取数据,进行赋值

<template>
  <div class="apper">
    <div class="aut">
      <button :class="{ 'btn': item.style == 8502, }" :title="item.desc" v-for="(item, index) in jsonData"
        :style="[styleObject[index], styleFont]" :key="item.num" @click="add(item)">
        {{ item.desc }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { Data } from '../assets/js/data.js'


const router = useRouter();
const jsonData = ref([]);
const posObject = ref({})
const fetchJsonData = async () => {
  try {
    // const response = await axios.get("./json/w2101.json");
    // jsonData.value = response?.data?.shape;
    jsonData.value = Data.shape;
  } catch (error) {
    console.error('Error fetching JSON data:', error);
  }
};

最后进行打包

npm run build

最后在dist文件中就不会出现单机html出现不显示的问题

总结:解决index.html打开空白的情况, 如果是axios请求打包完放在服务器中是没有问题的噢
1、路由改hash模式 history: createWebHashHistory (),
2、修改vue.config.js,添加publicPath的相关声明

3、使用的是本地路径(重点)

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值