Skip to content

Vite 插件

vite-aliases 插件

使用

在vite.config.js中配置别名,我们使用的是一下代码片段

js
export default defineConfig(() => {
  return {
    resolve: {
      alias: {
        //别名配置
        "~": path.resolve(__dirname, "./"),
        "@": path.resolve(__dirname, "./src"),
      }
    }
  }
})

简单实现

js
/**
 * 生成别名插件
 * */

const fs = require('fs')
const path = require('path')

function diffFileOrDir(filesArr = [], bashPath = '') {
  const result = {
    file: [],
    dir: []
  }

  filesArr.forEach(item => {
    const stat = fs.statSync(path.resolve(__dirname, bashPath + '/' + item))
    console.log(' =====', item, stat.isDirectory())
    if (stat.isDirectory()) {
      result.dir.push(item)
    } else {
      result.file.push(item)
    }
  })

  return result
}

function getSrcDir() {
  const result = fs.readdirSync(path.resolve(__dirname, '../src'))
  console.log(' =====', result)
  const diffResult = diffFileOrDir(result, '../src')
  console.log(' =====', diffResult)
  const resolveAliasesObj = {}
  diffResult.dir.forEach(item => {
    const key = `@${item}`
    resolveAliasesObj[key] = path.resolve(__dirname, '../src/' + item)
  })
  console.log(' =====', resolveAliasesObj)
  return resolveAliasesObj
}

export default () => {
  return {
    // 可以返回部分vite.config.js配置
    config(config, env) {
      // config 是 vite.config.js 的配置对象
      // env 是命令行传入的环境变量对象
      // console.log(' =====', config, env)
      // const result = getSrcDir()
      // return {
      //     resolve: {
      //         aliases: result
      //     }
      // }
      // 模拟返回特定配置
      return {
        resolve: {
          alias: {
            "~": path.resolve(__dirname, "./"),
            "@": path.resolve(__dirname, "./src"),
          }
        }
      }
    }
  }
}

vite-plugin-html 插件

使用

在vite.config.js中配置数据注入到html文件中

js
import {createHtmlPlugin} from 'vite-plugin-html'

export default defineConfig(() => {
  return {
    plugins: [
      createHtmlPlugin({
        inject: {
          data: {
            title: "首页",
          }
        }
      }),
    ]
  }
})

在index.html中使用,这个组件会替换掉title标签

html
    <title><%= title %></title>

简单实现

js
module.exports = (options) => {
  return {
    // html转换
    // transformIndexHtml: (html, ctx) => {
    //     console.log(' =====', html)
    //     return html.replaceAll(/<%= title %>/g, options.inject.data.title)
    // }
    transformIndexHtml: {
      // 执行的时机
      enforce: 'pre',
      transform(html, ctx) {
        // console.log('拦截到html等待调整 =====', html)
        return html.replace(/<%= title %>/g, options.inject.data.title)
      }
    }
  }
}

vite-plugin-mock 插件

使用

在项目根路径下创建一个mock.js文件,这是因为在vite的插件机制中,插件只能在项目根路径下运行

js
const mockJS = require('mockjs')

// 用mockjs模拟数据
const userList = mockJS.mock({
  'data|50': [{
    'name': '@cname',
    'email': '@email',
    'ip': '@ip',
    'domain': '@domain',
    'id': '@id',
    'avatar': '@image',
    'created_at': '@datetime',
    'updated_at': '@datetime',
    'age': '@integer(18, 80)',
    'address': '@region(true) @province(true) @city(true)',
    'cparagraph': '@cparagraph(2, 5)'
  }]
})

module.exports = [
  {
    method: 'get',
    url: '/api/users',
    response: ({body}) => {
      return {
        code: 200,
        message: 'success',
        data: userList
      }
    }
  },
]

然后将mock.js文件的路径配置到vite.config.js的plugins中即可

js
import {viteMockServe} from 'vite-plugin-mock'

export default defineConfig(() => {
  return {
    plugins: [
      viteMockServe()
    ]
  }
})

最后我们在项目当中发送请求即可

js
  fetch('/api/users').then(data => {
  data.json().then(function (data) {
    tableData.value = data.data.data
  })
})

简单实现

js
const fs = require('fs')
const path = require('path')

// mock插件
module.exports = (options) => {
  return {
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        // 先去读取mock里面的数据
        const mockData = getMockData()
        const isFlag = mockData.find(item => item.url === req.url)
        // console.log('判断请求的url在mock当中是否有配置 =====', req.url, '------', isFlag)
        // if (req.url === '/api/users') {
        if (isFlag) {
          // 这里的isFlag就是mock当中的一个对象 直接将对象的返回数据取出来,通过res.end返回给客户端
          const response = isFlag.response(req)
          // 设置请求头
          res.setHeader('Content-Type', 'application/json')
          // 会进入异步
          res.end(JSON.stringify(response))
        } else {
          next()
        }

      })
    }
  }
}

function getMockData() {
  // 去根路径下找mock文件
  const mockPath = fs.statSync(path.resolve(process.cwd(), 'mock'))
  const isDir = mockPath.isDirectory()
  // console.log('isDir =====', isDir)
  let mockResult = []
  if (isDir) {
    // 通过process.cwd()获取到根目录 再拼接文件路径进行获取
    mockResult = require(path.resolve(process.cwd(), 'mock/index.js'))
    // console.log('读取mock文件 =====', mockResult)
  }
  return mockResult
}

autoImport插件

使用

bash
npm i unplugin-auto-import -D

在vite.config.ts中配置,这里配置了vue作为全局指令,dts为生成的文件路径,

使用该插件在vue中使用时,就不要进行导入ref、reactive等指令了,直接使用即可

js
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig(() => {
  return {
    plugins: [
      AutoImport({
        imports: ['vue'],
        // 路径下自动生成文件夹存放全局指令
        dts: 'src/auto-import.d.ts'
      })
    ]
  }
})

auto.d.ts会自动生成,

auto-import.d.ts
ts
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
export {}
declare global {
  const EffectScope: typeof import('vue')['EffectScope']
  const computed: typeof import('vue')['computed']
  const createApp: typeof import('vue')['createApp']
  const customRef: typeof import('vue')['customRef']
  const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
  const defineComponent: typeof import('vue')['defineComponent']
  const effectScope: typeof import('vue')['effectScope']
  const getCurrentInstance: typeof import('vue')['getCurrentInstance']
  const getCurrentScope: typeof import('vue')['getCurrentScope']
  const h: typeof import('vue')['h']
  const inject: typeof import('vue')['inject']
  const isProxy: typeof import('vue')['isProxy']
  const isReactive: typeof import('vue')['isReactive']
  const isReadonly: typeof import('vue')['isReadonly']
  const isRef: typeof import('vue')['isRef']
  const markRaw: typeof import('vue')['markRaw']
  const nextTick: typeof import('vue')['nextTick']
  const onActivated: typeof import('vue')['onActivated']
  const onBeforeMount: typeof import('vue')['onBeforeMount']
  const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
  const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
  const onDeactivated: typeof import('vue')['onDeactivated']
  const onErrorCaptured: typeof import('vue')['onErrorCaptured']
  const onMounted: typeof import('vue')['onMounted']
  const onRenderTracked: typeof import('vue')['onRenderTracked']
  const onRenderTriggered: typeof import('vue')['onRenderTriggered']
  const onScopeDispose: typeof import('vue')['onScopeDispose']
  const onServerPrefetch: typeof import('vue')['onServerPrefetch']
  const onUnmounted: typeof import('vue')['onUnmounted']
  const onUpdated: typeof import('vue')['onUpdated']
  const provide: typeof import('vue')['provide']
  const reactive: typeof import('vue')['reactive']
  const readonly: typeof import('vue')['readonly']
  const ref: typeof import('vue')['ref']
  const resolveComponent: typeof import('vue')['resolveComponent']
  const shallowReactive: typeof import('vue')['shallowReactive']
  const shallowReadonly: typeof import('vue')['shallowReadonly']
  const shallowRef: typeof import('vue')['shallowRef']
  const toRaw: typeof import('vue')['toRaw']
  const toRef: typeof import('vue')['toRef']
  const toRefs: typeof import('vue')['toRefs']
  const toValue: typeof import('vue')['toValue']
  const triggerRef: typeof import('vue')['triggerRef']
  const unref: typeof import('vue')['unref']
  const useAttrs: typeof import('vue')['useAttrs']
  const useCssModule: typeof import('vue')['useCssModule']
  const useCssVars: typeof import('vue')['useCssVars']
  const useSlots: typeof import('vue')['useSlots']
  const watch: typeof import('vue')['watch']
  const watchEffect: typeof import('vue')['watchEffect']
  const watchPostEffect: typeof import('vue')['watchPostEffect']
  const watchSyncEffect: typeof import('vue')['watchSyncEffect']
}
// for type re-export
declare global {
  // @ts-ignore
  export type {
    Component,
    ComponentPublicInstance,
    ComputedRef,
    ExtractDefaultPropTypes,
    ExtractPropTypes,
    ExtractPublicPropTypes,
    InjectionKey,
    PropType,
    Ref,
    VNode,
    WritableComputedRef
  } from 'vue'
  import('vue')
}

By Modify.