vue-cli项目和vite项目实现功能需要知道的一些事情

345 阅读2分钟

1、环境变量

vue-cli项目

.env.development为例,vue-cli默认会加载NODE_ENVBASE_URL和以 VUE_APP_ 开头的变量注入到客户端代码中;

VUE_APP_HELLO=hello

当然如果你不希望走这个环境变量配置文件,你完全可以自己通过改webpack配置来实现,具体代码如下vue.config.js:

module.exports = {
  // ...other
  chainWebpack(config) {
      // ...other
      config.plugin('define').tap(args => {
      console.log(args);
      args[0]['process.env']['WORLD'] = JSON.stringify('world')
      return args
    })
  },
};

在你的业务代码中,你完全可以直接通过process.env.xxxx的形式来使用变量,这里需要注意的是改webpack插件那个变量的值必须要用JSON.stringify包裹一下。

vite项目

vite中,你需要在env.development中以VITE_开头声明即可,例如:

VITE_HELLO=hello

区别是在使用的时候就不能通过process.env去读取了,而是要通过import.meta.env.VITE_HELLO来读取了;如果你不喜欢这个前缀,你可以通过更改vite配置envPrefix(但是真没必要)来做。

2、文件名后缀省略问题

vue-cli项目

vue-cli项目中,默认就帮我们实现了多种webpackextensions,比如常见的` '.mjs','.js','.jsx','.vue','.json'等等

vite项目

vite中,.vue这种后缀是不支持的,因为如果省略,会导致ide对类型提示出错,所以vue官方不推荐省略,而最好是带上全称

3、怎么实现svg-icon

首先先实现一个svg-icon组件

SvgIcon.vue

<template>
  <svg class="svg-icon" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
export default {
  name: "SvgIcon",
  props: {
    name: {
      type: String,
      required: true,
    },
  },
  computed: {
    iconName() {
      return `#icon-${this.name}`;
    },
  },
};
</script>

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

vue-cli项目

vue-cli需要借助svg-sprite-loader这个插件来实现,具体配置如下:vue.config.js

const path = require("path");
const resolve = function (dir) {
  return path.resolve(__dirname, dir);
};
module.exports = {
  
  chainWebpack(config) {
    // 其他...
    config.module.rule("svg").exclude.add(resolve("src/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();
      
     // other
  },
};

使用

<svg-icon name="facebook"></svg-icon>

vite项目

vite项目主要是借助vite-plugin-svg-icons来实现,具体配置如下:vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(),
  
    createSvgIconsPlugin({
      // Specify the icon folder to be cached
      iconDirs: [path.resolve(process.cwd(), 'src/icons')],
      // Specify symbolId format
      symbolId: 'icon-[name]',
    }),
  ]
})

将下面这行代码贴到main.js中

import 'virtual:svg-icons-register'

最后就能使用原来的svg-icon组件了

4、怎么实现组件的自动注册

vue-cli

export default Vue => {
  const req = require.context("./", false, /\.vue$/);
  const requireAll = (requireContext) => {
    requireContext.keys().map((v) => {
      const fileName = v.replace("./", "").split(".")[0];
      Vue.component(fileName, req(v).default);
    });
  };
  requireAll(req);
};

vite

import { defineAsyncComponent } from "vue"
export default {
    install: (app) => {
        const modules = import.meta.glob('./*.vue')

        for (const [filename,fn] of Object.entries(modules)) {
            let name = filename.replace('./','').split('.')[0]
            app.component(name,defineAsyncComponent(fn))
        }
    }
}

二者都使用了插件化,虽然一个是vue2,一个是vue3,但是基本都是拿来即用的。

其实二者还有许多可以比较参考学习的地方,这里先列这些,后面想到再补充,这里都可以复制直接使用的。