vite中手写几个简易的插件demo

文章目录

  • 1.vite中如何配置插件
  • 2.插件
    • 1. vite-plugin-mock,数据模拟(类似mockjs)
    • 2. vite-plugin-aliases,文件夹别名(@ ==src)

1.vite中如何配置插件

src同级目录创建plugins文件夹,然后在plugins文件夹下面创建[filename].js文件,最后在vite.config.js或者vite.config.ts中引入,例如

//vite.config.js | vite.config.ts
import vitePluginMock from "./plugins/vite-plugin-mock"

2.插件

1. vite-plugin-mock,数据模拟(类似mockjs)

//vite-plugin-mock.js
/**@type {import('vite').UserConfig}**/
/**@type {import('node:fs')}**/
/**@type {import('node:path')}**/
const fs = require('node:fs');
const path = require('node:path');

// 默认配置
const defaultOptions = {
  enabled: process.env.NODE_ENV === 'development',
};

module.exports = (options) => {
  const newOptions = { ...defaultOptions, ...options };
  return {
    configureServer: (serve) => {
      const middleware = serve.middlewares;
      const isExistDir = fs.existsSync('mock/index.js');
      const mockDescriptors = require(path.resolve(process.cwd(), 'mock/index.js'));
      const isAvailable = Array.isArray(mockDescriptors) && mockDescriptors.length > 0;

      middleware.use((req, res, next) => {
        if (!newOptions.enabled) {
          throw new Error(`[vite]: current environment is ${process.env.NODE_ENV}`);
        }
        const reqUrl = req.url;
        if (isExistDir && isAvailable) {
          const mockDescriptor = mockDescriptors.find((mockItem) => mockItem.url === reqUrl);
          if (mockDescriptor) {
            const response = mockDescriptor?.response() || {};
            res.setHeader('Content-type', 'application/json');
            res.end(JSON.stringify(response));
          } else {
            next();
          }
        } else {
          console.log(`[vite]:mock directory is not found`);
          next();
        }
      });
    },
  };
};

2. vite-plugin-aliases,文件夹别名(@ ==src)

//vite-plugin-aliases.js
/** @type {import('vite').UserConfig} */
/** @type {import('node:path')} */
/** @type {import('node:fs')} */
const path = require('node:path');
const fs = require('node:fs');

function filterFilesFndFolders(files) {
  const dirs = files.filter((fileName) => {
    const fileStat = fs.statSync(path.join(__dirname, '../src', fileName));
    if (fileStat.isDirectory()) return fileName;
  });
  return dirs;
}

function getAliasOptions(keyName) {
  const srcPath = path.join(__dirname, '../src');
  const files = fs.readdirSync(srcPath);
  const result = filterFilesFndFolders(files);
  const aliasObj = {};
  aliasObj[`${keyName}`] = srcPath;
  result.forEach((dir) => {
    aliasObj[`${keyName}${dir}`] = path.join(srcPath, dir);
  });
  return aliasObj;
}

module.exports = ({ keyName = '@' } = {}) => {
  return {
    name: 'vite-aliases',
    config: (config, env) => {
      return {
        resolve: {
          alias: getAliasOptions(keyName),
        },
      };
    },
  };
};

你可能感兴趣的:(vue,html,js,前端,javascript,vue.js)