vue2项目将webpack迁移为vite,并使用svg, 完美解决所有bug

背景
1. vite是跟随vue3诞生的一个工具,它让我们在开发环境中的效率大大提升,其原因是因为它省去了我们在开发环境中的打包过程(因为我们在实际开发环境中是不需要打包的,但是webpack却会去执行打包,大大降低了开发效率),将ES 模块源码直接传输给浏览器,浏览器使用自带的 <script module> 进行解析支持
2. 但是vite其实是基于vue3进行开发的,很多时候我们的老项目使用的都是vue2版本的,这个时候想要使用vite应该怎么做呢
过程
1. 通过vite创建vue项目
npm init @vitejs/app
2. 选择vue模板(还支持react, vanilla, svelte, preact等)
3. 安装老项目中使用到的npm包

注意::这里也安装老项目中的vue2版本,比如我用的是vue2.5.2版本的
在这里插入图片描述

4. 将老项目中的src文件复制到vite项目中,并运行
5. 此时运行项目,通常情况下会报错,这个报错信息是因为vite.config.js中使用到的插件仅支持vue3版本以上,所以此时我们需要安装一个支持vue2的插件

在这里插入图片描述

支持vue2的插件,并修改vite.config.js文件
npm install vite-plugin-vue2 -D

在这里插入图片描述

此时运行项目,发现还会报错,(别急有报错说明还有希望,没报错就GG了,哈哈哈);根据报错信息知道,找不到vue-template-compiler模块,因此我们安装一下即可

在这里插入图片描述

npm install vue-template-compiler -D
安装后再运行项目,发现页面没有出来,打开控制台,又报错。。。,这次是因为找不到#app元素,vue2中挂载dom元素的方式在vite中并未生效,因此我们需要修改main.js中挂载根元素的方式

在这里插入图片描述
在这里插入图片描述

6. 项目运行后,会发现此时接口请求报错(出现跨域问题,或者404),这是因为vue中代理和vite中代理有区别,需要配置成vite规定的代理
server: {
		port: 8081, // 自己本地需要运行的端口
		fs: { // 不对根目录访问做限制
			strict: false,
		},
		proxy: {
			'/Index': { // 不要写成根路径!!!否则会直接跳转到线上地址
				target: 'http://www.需要代理的地址/',
				changeOrigin: true,
				rewrite: (path) => path.replace(/^\//, '') // 不要写成rewrite: (path) => path.replace(/^\/Index/, '')!!!否则会报404
			},
			'/Home': { // 不要写成根路径!!!否则会直接跳转到线上地址
				target: 'http://www.需要代理的地址/',
				changeOrigin: true,
				rewrite: (path) => path.replace(/^\//, '')
			},
		}
	},
此时再运行,成功!!!!(喜大普奔有没有)
============================ vite 增加svg插件使用 =============================
vite中使用svg图
1.安装插件
npm i vite-plugin-svg-icons -D
2.配置vite.config.js文件, 并在src下新建文件夹icons,放入要使用的 .svg图片,如下:
// 引入
import viteSvgIcons from 'vite-plugin-svg-icons'

// 插件配置
plugins: [
	viteSvgIcons({
		iconDirs: [path.resolve(process.cwd(), 'src/icons')], // 在src下新建文件夹icons
		symbolId: 'icon-[dir]-[name]'
	})
],

在这里插入图片描述

注意:如果使用 import viteSvgIcons from 'vite-plugin-svg-icons’报错,则需要换成这种写法
import { createSvgIconsPlugin } from ‘vite-plugin-svg-icons’

 createSvgIconsPlugin({
     iconDirs: [path.resolve(process.cwd(), 'src/icons')], // 在src下新建文件夹icons
     symbolId: 'icon-[dir]-[name]'
   })
3. components下新建SvgIcon.vue文件,增加内容
<template>
	<svg aria-hidden="true">
		<use :href="symbolId" :fill="color" />
	</svg>
</template>

<script>
	export default {
		name: 'SvgIcon',
		props: {
			prefix: {
				type: String,
				default: 'icon',
			},
			name: {
				type: String,
				required: true,
			},
			color: {
				type: String,
				default: '#333',
			},
		},
		data() {
			return {
				symbolId: ''
			}
		},
		mounted() {
			this.symbolId = `#${this.prefix}-${this.name}`
		},
	}
</script>

<style scoped>
	svg { // 根据开发需求设置css
		width: 20px;
		height: 20px;
	}
</style>

注意⚠️:vue3中SvgIcon组件代码这么写

<template>
  <svg aria-hidden="true" class="svg-icon" :width="props.size" :height="props.size">
    <use :xlink:href="symbolId" rel="external nofollow" :fill="props.color" />
  </svg>
</template>
 
<script setup>
import { computed } from 'vue'
const props = defineProps({
  prefix: {
    type: String,
    default: 'icon'
  },
  name: {
    type: String,
    required: true
  },
  color: {
    type: String,
    default: '#ffffff'
  },
  size: {
    type: String,
    default: '1rem'
  }
})
const symbolId = computed(() => `#${props.prefix}-${props.name}`)
</script>

<style scoped>
svg {
  width: 16px;
  height: 16px;
}
</style>
4.main.js中引入
import 'virtual:svg-icons-register'
5.全局注册svg
// main.ts中引入

import SvgIcon from './components/SvgIcon.vue'

createApp(App)
.use(router)
.component('svg-icon', SvgIcon)
.mount('#app')
6.组件中使用svg

在这里插入图片描述

template使用

在这里插入图片描述

效果图,正常显示。

在这里插入图片描述

如果要修改svg颜色,修改icons下 如account.svg中的fill字段为currentColor

在这里插入图片描述

页面中设置样式的color即可

在这里插入图片描述

  • 1
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Vue 项目使用 webpack 将多个组件合并打包并实现按需加载,需要使用 webpack 的 code splitting 功能。具体步骤如下: 1. 在 webpack 配置文件中配置 code splitting: ```javascript // webpack.config.js module.exports = { // ... optimization: { splitChunks: { chunks: 'async', minSize: 30000, maxSize: 0, minChunks: 1, maxAsyncRequests: 5, maxInitialRequests: 3, automaticNameDelimiter: '~', name: true, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendor', chunks: 'all' }, common: { name: 'common', minChunks: 2, chunks: 'all', priority: -10, reuseExistingChunk: true } } } } }; ``` 2. 在组件中使用 `import()` 动态导入其他组件: ```javascript // MyComponent.vue export default { methods: { handleClick() { import('./OtherComponent.vue').then(module => { const OtherComponent = module.default; // 使用 OtherComponent 组件 }); } } }; ``` 3. 在模板中使用 `v-if` 或 `v-show` 按需显示组件: ```html <template> <div> <button @click="showOther">Show Other Component</button> <OtherComponent v-if="show" /> </div> </template> <script> export default { data() { return { show: false }; }, methods: { showOther() { import('./OtherComponent.vue').then(module => { const OtherComponent = module.default; this.show = true; }); } } }; </script> ``` 这样,webpack 会根据配置将多个组件打包成多个文件,并在需要时动态加载。注意,`import()` 返回的是一个 Promise,需要使用 `then()` 方法获取模块的导出值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值