1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Vue 2 中 使用Vite作为前端构建开发工具 替代webpack(一)——vite.config.js配置文件

Vue 2 中 使用Vite作为前端构建开发工具 替代webpack(一)——vite.config.js配置文件

时间:2022-10-13 09:54:05

相关推荐

Vue 2 中 使用Vite作为前端构建开发工具 替代webpack(一)——vite.config.js配置文件

Vue 2 中,使用Vite作为前端构建开发工具,替代webpack(一)——vite.config.js配置文件

当前版本vite@2.3.7vite@2.4.4

"vite": "^2.4.4",

一、 适合什么项目迁移

使用 vue2 的系统内部系统 - 无需大型流量场景:因为 vite 更迭较快,导致系统需要定期改动基础功能,造成不稳定非 ssr 系统 - ssr 还有很多问题,暂且等社区丰富起来定期有人维护的系统对开发有痛点而想要改进:比如打包慢,冷启动慢,HMR 更新慢。。。。vite 生产环境用 rollup,但是改造成本大,提效不高,风险大,暂不建议使用。

二、迁移步骤

将会以内部系统作为案例改造, 开发用 vite,生产依旧保持 webpack。

简单了解 vite 特性。有问题优先看vite 官网排查是否有更新或解决方案!!npm i vite@2.3.7 vite-plugin-vue2@1.6.2 vite-plugin-html@2.0.7 -Dpackage.json 添加一个 script – “vite”: “NODE_ENV=development vite”关键在于配置 vite.config.js【默认叫做这个文件名,可配置成其他的】

根目录下,vite.config.js配置文件

import {defineConfig } from 'vite';import path from 'path';import fs from 'fs';import {createVuePlugin } from 'vite-plugin-vue2';import {injectHtml, minifyHtml } from 'vite-plugin-html';import {cjs2esmVitePlugin } from 'cjs2esmodule'import dotenv from 'dotenv'const config = require('./config')try {// 根据环境变量加载环境变量文件const file = dotenv.parse(fs.readFileSync(`./config/.env.${process.env.NODE_ENV}`), {debug: true})console.log(file)// 根据获取的 key 给对应的环境变量赋值for (const key in file) {process.env[key] = file[key]}} catch (e) {console.error(e)}const API_LOCATION = process.env.API_LOCATION || '/api'function resolve(dir) {return path.join(__dirname, './', dir)}export default defineConfig({root: './', // 项目根目录(index.html 文件所在的位置)可以是一个绝对路径,或者一个相对于该配置文件本身的相对路径。publicDir: 'public', // 作为静态资源服务的文件夹.该值可以是文件系统的绝对路径,也可以是相对于项目的根目录的相对路径。base: './', // 公共基础路径。改值可以是绝对路径或空字符串mode: 'development',optimizeDeps: {// 要预构建的第三方依赖include: []},resolve: {alias: {// 'vue': 'vue/dist/vue.esm.js', // 如果是模板解析的 - 使用这个 vue:内部为正则表达式 vue 结尾的'vendor': resolve('src/vendor'),'@': resolve('src'),'~@': resolve('src'),'~component': resolve('src/components'),'~config': resolve('config'),}},plugins: [cjs2esmVitePlugin(), // 将 commonjs 转化为 es module: 有报错createVuePlugin({jsx: true,jsxOptions: {injectH: false,},}),minifyHtml(), // 压缩 HTMLinjectHtml({// 入口文件 index.html 的模板注入injectData: {// 模板注入的数据htmlWebpackPlugin: {options: {isVite: true,shotcut: '/static/img/favicon.png',}},title: 'HMO 运营后台',},}),],define: {'process.env': process.env},server: {host: '',open: true, // 是否自动打开浏览器port: process.env.PORT || config.dev.port,proxy: {[API_LOCATION]: {target: 'http://127.0.0.1:8001',rewrite: (path) => path.replace(API_LOCATION, '')}}},});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。