溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue?Cli項目怎么重構(gòu)為Vite

發(fā)布時間:2023-04-21 16:12:55 來源:億速云 閱讀:104 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Vue Cli項目怎么重構(gòu)為Vite”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Vue Cli項目怎么重構(gòu)為Vite”吧!

我們知道 VueCli 使用的是 webpack 打包工具,而 Vite 是基于 ESM 的打包工具,所以我們可以使用 Vite 來替換 VueCli,來提升我們的開發(fā)體驗。

更新依賴與 package.json

我們先將項目中的 VueCli 相關(guān)依賴刪除,然后安裝 Vite 相關(guān)依賴。

::: tip 包管理工具我們使用 pnpm,如果你使用的是 npmyarn,請自行替換。 :::

  • 刪除 VueCli 相關(guān)依賴

pnpm remove @vue/cli-plugin-babel @vue/cli-plugin-eslint @vue/cli-service
  • 安裝 Vite 相關(guān)依賴

::: warning 注意 如果你用的是 vue2.6, 請安裝 vite-plugin-vue2, 并且不需要 jsx 支持 :::

pnpm add -D vite @vitejs/plugin-vue @vitejs/plugin-vue2 @vitejs/plugin-vue2-jsx
  • 同時我們可以移除 babel 相關(guān)依賴

pnpm remove -D babel-plugin-dynamic-import-node babel-eslint
  • 修改 scripts

修改 package.json 中的 scripts

{
  "scripts": {
    "dev": "vite --host",
    "build:prod": "vite build",
    "build:stage": "vite build --mode staging"
  }
}

配置 Vite

  • 創(chuàng)建 vite.config.js,并添加基本配置

import { defineConfig, loadEnv } from 'vite';
// 如果使用的是 vue2.6, 請使用 vite-plugin-vue2
// import { createVuePlugin as vue } from 'vite-plugin-vue2';
import vue from '@vitejs/plugin-vue2';
import { resolve } from 'path';
import rollupNodePolyFill from 'rollup-plugin-node-polyfills';
import { dataToEsm } from '@rollup/pluginutils';
import vueJsx from '@vitejs/plugin-vue2-jsx';

export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };

  return defineConfig({
    plugins: [
      // vue2.6
      // vue({ jsx: true }),
      // vue2.7
      vue(),
      vueJsx(),
    ],
    server: {
      port: 75,
      proxy: {
        [process.env.VITE_APP_BASE_API]: {
          target: process.env.VITE_APP_PROXY_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${process.env.VITE_APP_BASE_API}`), ''),
        },
      },
    },
    resolve: {
      alias: {
        '@': resolve('src'),
      },
      extensions: ['.js', '.vue', '.json'],
    },
  });
};
  • 如果你的項目中使用了 node 的一些模塊,需要在 resolve.alias 中添加對應(yīng)的 polyfill

::: tip 提示 需要添加 rollup-plugin-node-polyfills 依賴 :::

defineConfig({
  // ...
  resolve: {
    alias: {
      '@': resolve('src'),
      // 如果你的項目中使用了node的一些模塊,需要在這里添加對應(yīng)的polyfill,如沒有配置.js的extensions,需要在末尾添加.js
      path: 'rollup-plugin-node-polyfills/polyfills/path',
  }
})
  • 如果你的項目需要使用 build 的配置,可以參考如下配置

defineConfig({
  // ...
  build: {
    rollupOptions: {
      output: {
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash][extname]',
        // 分離依賴包
        manualChunks: {
          vue: ['vue'],
          echarts: ['echarts'],
          'element-ui': ['element-ui'],
        },
      },
    },
  },
});
  • 移除 vue.config.js

  • 若你的項目中使用了 jsx,請將 '.js' 文件修改為 '.jsx'

全局替換 Env 變量與 require

  • 將所有的 process.env 替換為 import.meta.env,如:

// 替換前
const uploadFileUrl = process.env.VUE_APP_BASE_API + '/upload';
// 替換后
const uploadFileUrl = import.meta.env.VITE_APP_BASE_API + '/upload';

::: tip 參考正則 process\.env\.VUE_APP_ replace import.meta.env.VITE_APP_ :::

::: danger 注意 請勿將 vite.config.js 中的 process.env 替換為 import.meta.env :::

  • 將所有直接導(dǎo)入的 require 替換為 import,如:

// 替換前
const { version } = require('../../package.json');
// 替換后
import { version } from '../../package.json';

::: tip 參考正則 const\s+\{(.+?)\}\s+=\s+require\((.+?)\); replace import {$1} from $2; :::

  • 移除動態(tài)導(dǎo)入的 require.context,如:

// 替換前
const svgIcons = require.context('@/assets/icons/svg', false, /\.vue$/);
// 替換后
const svgIcons = import.meta.globEager('@/assets/icons/svg');
  • 動態(tài)導(dǎo)入的 Vue 路由組件需要調(diào)整為 import(),如:

// 替換前
route.component = () => require([`@/views/${route.component}`]);
// 替換后

// 動態(tài)導(dǎo)入
const views = import.meta.glob('@/views/**/**.vue');
route.component = views[`@/views/${route.component}.vue`];

// 確定文件路徑的動態(tài)導(dǎo)入
// 替換前
route.component = () => require('@/views/index/index');
// 替換后
route.component = () => import('@/views/index/index.vue');

調(diào)整 ESLint 配置

移除 babel-eslint parser

// .eslintrc.js
module.exports = {
  // ...
  // 移除
  // parser: 'babel-eslint',
  // ...
};

調(diào)整 index.html

移動 public/index.htmlindex.html,并添加 JavaScript 模塊 的引入方式

<!-- ... -->
<script type="module" src="/src/main.js"></script>
<!-- ... -->

::: tip 提示 <script>標(biāo)簽一般添加在 </body> 前 :::

SVG 支持

  • 安裝依賴

pnpm add -D vite-plugin-svg-icons
  • 修改 vite.config.js,參考配置如下:

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

defineConfig({
  // ...
  plugins: [
    // ...
    createSvgIconsPlugin({
      // 圖標(biāo)文件夾中,所有的svg文件將被轉(zhuǎn)換為svg精靈
      iconDirs: [resolve(process.cwd(), 'src/assets/icons/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
    }),
  ],
});
  • 添加虛擬模塊至入口文件,如:

// src/main.js
// ...
import 'virtual:svg-icons-register';
// ...
  • 添加 SvgIcon/index.vue 組件

<template>
  <div v-if="isExternal" : class="svg-external-icon svg-icon" v-on="$listeners" />
  <svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" rel="external nofollow"  />
  </svg>
</template>

<script>
import { isExternal } from '@/utils/validate';

export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: '',
    },
  },
  computed: {
    isExternal() {
      return isExternal(this.iconClass);
    },
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className;
      } else {
        return 'svg-icon';
      }
    },
    styleExternalIcon() {
      return {
        mask: `url(${this.iconClass}) no-repeat 50% 50%`,
        '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`,
      };
    },
  },
};
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>

感謝各位的閱讀,以上就是“Vue Cli項目怎么重構(gòu)為Vite”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Vue Cli項目怎么重構(gòu)為Vite這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI