Vite 插件开发实战:如何自动注入 SDK 脚本

0 阅读1分钟

需求背景

AutoForm SDK 开发完成后,我们需要提供给客户集成。 对于使用 Vite 的客户,如果能提供一个插件,让他们在 vite.config.ts 里配置一下就能用,体验会好很多。

本文将手把手教你开发一个 Vite 插件,实现 SDK 脚本的自动注入。

插件结构

Vite 插件本质上是一个返回特定对象的函数。

// vite-plugin-autoform.ts
export default function autoFormPlugin(options) {
  return {
    name: 'vite-plugin-autoform',
    // 插件钩子
    transformIndexHtml(html) {
      // ...
    }
  };
}

核心逻辑:transformIndexHtml

我们需要在 index.html<body> 结束标签前插入 SDK 的 <script> 标签。

transformIndexHtml(html) {
  const scriptTag = `
    <script>
      window.AIFormConfig = ${JSON.stringify(options)};
    </script>
    <script src="https://cdn.autoform.com/sdk.js" async></script>
  `;
  
  return html.replace('</body>', `${scriptTag}</body>`);
}

进阶:开发环境与生产环境区分

在开发环境(npm run dev)下,我们可能希望注入本地的 SDK 脚本,方便调试。

configResolved(config) {
  isDev = config.command === 'serve';
},

transformIndexHtml(html) {
  const src = isDev 
    ? 'http://localhost:3000/sdk.js' 
    : 'https://cdn.autoform.com/sdk.js';
    
  // ...
}

发布到 NPM

  1. 创建 package.json
  2. 配置 maintypes
  3. npm publish

现在,用户只需要:

npm install vite-plugin-autoform

然后在 vite.config.ts 中:

import autoForm from 'vite-plugin-autoform';

export default {
  plugins: [autoForm({ token: 'xxx' })]
};

总结

Vite 插件开发非常简单,但能极大地提升用户体验。对于 SDK 开发者来说,提供配套的构建工具插件是必不可少的。

👉 官网地址:51bpms.com