06- Vite所使用的插件(学习vite打包工具的笔记)

116 阅读3分钟

一、vite-aliases官方网址

1. 作用

vite-aliases可以帮助我们自动生成别名

2.使用方法

Install

npm i vite-aliases -D

Add it to vite.config.js

// vite.config.js
import { ViteAliases } from 'vite-aliases'

export default {
	plugins: [
		ViteAliases()
	]
};
3.原理实现Plugin API | Vite (vitejs.dev)config

插件就是在不同生命周期做不同的事

在 config()生命周期中 添加alias别名

// vite的插件必须返回给vite一个配置对象
const fs = require("fs");
const path = require("path");

function diffDirAndFile(dirFilesArr = [], basePath = "") {
    const result = {
        dirs: [],
        files: []
    }
    dirFilesArr.forEach(name => {
        // 我直接用异步的方式去写的
        const currentFileStat = fs.statSync(path.resolve(__dirname, basePath + "/" + name));
        console.log("current file stat", name, currentFileStat.isDirectory());
        const isDirectory = currentFileStat.isDirectory();

        if (isDirectory) {
            result.dirs.push(name);
        } else {
            result.files.push(name);
        }

    })

    return result;
}

function getTotalSrcDir(keyName) {
    const result = fs.readdirSync(path.resolve(__dirname, "../src"));
    const diffResult = diffDirAndFile(result, "../src");
    console.log("diffResult", diffResult);
    const resolveAliasesObj = {}; // 放的就是一个一个的别名配置 @assets: xxx
    diffResult.dirs.forEach(dirName => {
        const key = `${keyName}${dirName}`;
        const absPath = path.resolve(__dirname, "../src" + "/" + dirName);
        resolveAliasesObj[key] = absPath;
    })

    return resolveAliasesObj;
}

module.exports = ({
    keyName = "@"
} = {}) => {
    return {
        config(config, env) {
            // 只是传给你 有没有执行配置文件: 没有
            console.log("config", config, env);
            // config: 目前的一个配置对象
            // production  development  serve build yarn dev yarn build 
            // env: mode: string, command: string
            // config函数可以返回一个对象, 这个对象是部分的viteconfig配置【其实就是你想改的那一部分】
            const resolveAliasesObj = getTotalSrcDir(keyName);
            console.log("resolve", resolveAliasesObj);
            return {
                // 在这我们要返回一个resolve出去, 将src目录下的所有文件夹进行别名控制
                // 读目录
                resolve: {
                    alias: resolveAliasesObj
                }
            };
        }
    }
}

二、vite-plugin-html官网网址

1. 作用

帮我们动态的去控制整个html文件中内容

2.使用方法
  1. 使用的是ejs语法 <%= title %>在index.html中

ejs在服务端会用的比较频繁 因为服务端可能经常会动态的去修改index.html的内容

  1. 下载依赖并且vite.config.js配置
npm i vite-plugin-html -D
import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
    plugins: [
          createHtmlPlugin({
              inject: {
                  data: {
                      title:"首页"
                  }
              }
          })
    ]
})
3.实现原理Plugin API | Vite (vitejs.dev)transformIndexHtml
module.exports = (options) => {
  return {
    // 转换html的 
    // 将我们插件的一个执行时机提前 
      transformIndexHtml: {
      enforce: "pre",
      transform: (html, ctx) => {
        // ctx 表示当前整个请求的一个执行期上下文: api /index.html  /user/userlist json  get post headers
        console.log("html", html);
  
        return html.replace(/<%= title %>/g, options.inject.data.title);
      }
    }
    }
}

三、vite-plugin-mock官网地址

模拟后端数据方便开发

2. 使用方法
npm i  mockjs -S  npm i vite-plugin-mock -D
import { viteMockServe } from 'vite-plugin-mock'

export default ({ command }: ConfigEnv): UserConfigExport => {
  return {
    plugins: [
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve',
      }),
    ],
  }
}

创建模拟后端数据 mock.js

const mockJS = require("mockjs");

const userList = mockJS.mock({
  "data|100": [{
    name: "@cname", // 表示生成不同的中文名
    // ename: mockJS.Random.name(), // 生成不同的英文名
    "id|+1": 1, // 
    time: "@time",
    date: "@date"
  }]
})

module.exports = [
  {
    method: "post",
    url: "/api/users",
    response: ({ body }) => {
      // body -> 请求体 
      // page pageSize body
      return {
        code: 200,
        msg: "success",
        data: userList
      };
    }
  },
]

四、vite-plugin-federation 联邦webpack5提出

1. 作用

模块联邦主要用于微前端的架构体系中, 他允许你在两个不同的项目中采用公用模块以及进行模块复用

项目A

// project a webpack config
const { ModuleFederationPlugin } = require("webpack").container;
module.exports = {
    plugins: [
        new ModuleFederationPlugin({
            name: "module", // 你要暴露出去的公用模块的名称
            filename: "module-entry.js", // 你暴露出去的公用模块最终会打包到一个js文件里, 你可以配置这个js文件名
            exposes: {
                // 具体暴露的模块
                "./cloneDeep": "./src/cloneDeep.js"
            }
        })
    ]
}

项目B

// project b webpack config
module.exports = {
    plugins: [
        new ModuleFederationPlugin({
            remotes: {
                moduleA: "module@http:localhost:8080/cloneDeep.js", // 就引入了, 然后导入的时候直接module/cloneDeep就好了
            }
        })
    ]
}