一、index.html页面无法渲染
我们都知道vue项目入口是由main.js、app.vue、index.html三者组合而成的,具体的逻辑就是webpack将main.js、app.vue打包成一个js,然后再将js插入到index.html中。
如果main.js是默认路径,那没有问题。但是我们有时候会想要修改main.js的路径,方便我们代码的管理。如果没有修改webpack配置,那首先会找不到main.js然后项目启动起来后,index.html是为空的。
这个问题去修改vue.config.js的配置,由于vue现在打包的代码结构有变化已经没有webpack.config.js文件了,取而代之的是vue.config.js,所以我们去配置vue.config.js文件即可。如果没有就去在src同级目录创建文件。
配置文件如下:
const {
defineConfig} = require('@vue/cli-service');
const path = require('path');
const getEnv = require('env-parse').getEnv;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {
VueLoaderPlugin} = require('vue-loader');
module.exports = defineConfig({
transpileDependencies: true,
outputDir: "dist",
assetsDir: "static",
lintOnSave: false,
filenameHashing: true,
pages: {
defineConfig: {
entry: 'src/js/conf/main.js'//修改默认的main文件路径
}
},
devServer: {
port: 8963,
proxy: {
'/api': {
timeout: 3600,
target: getEnv('BASE_URL', 'https://localhost:12345'),
changeOrigin: true
}
}
},
chainWebpack:(config)=>{
config.resolve.alias.set('@',path.resolve(__dirname,'src/js')).set('~',path.resolve(__dirname,'src')).set('jquery',path.resolve(__dirname,'jquery'));
},
configureWebpack: (config)=>{
config.plugins = [
new VueLoaderPlugin(),//加载vue文件的插件
new HtmlWebpackPlugin({
//!!!index.html文件 重点
title:'购物商城',
template:'public/index.html',//入口替换文件
filename:'index.html',//html输出文件
inject:'body'
})
]
}
})
修改配置文件的重点主要是entry:xxx.js
和htmlWebpackPlugin
这两个。
二、项目启动后访问报错
报错1:
这个错误的原因是因为我的vue版本是3.0,而use是2.0所使用的方法。只需要改为3.0对应的方法即可。
import {
createApp} from 'vue'
const app = createApp({
});
app.use(xxx)
现在use的使用方法就是这样,当然不同的组件对应的创建组件方法也有所改变。比如说vue-router和vuex,都不能使用原先的创建方法,而是要使用createRouter、createStore的方式。
代码如下:router/index.js
import HomeView from '../../../views/HomeView.vue'
import {
createRouter,createWebHistory} from 'vue-router';
const routes = [
{
path: '/home',
name: 'HomeView',
component: HomeView
}
]
const vueRouter = createRouter({
history:createWebHistory(),
routes
})
export default vueRouter
store/index.js
import {
createApp} from 'vue'
import {
createStore} from 'vuex'
import goods from './goods'
import order from './order'
import user from './user'
const store = createStore({
modules:{
goods,
order,
user
}
})
const app = createApp();
app.use(store);
不过要注意的是,这种方法都只支持4.0的版本,否则会提示cannot resolve
只需要安装对应的版本即可。
npm install vuex@4
npm install vue-router@4

我将vue2.0版本的代码挪过来自己用,就导致了一系列的问题。