打包和发布 | 青训营笔记

99 阅读2分钟

这是我参与「 第五届青训营 」伴学笔记创作活动的第 4 天

组件库:打包发布

一、全量打包

1、编写一个创建脚本(build.js)

  • 参考vite官方文档的Library Mode

  • package.json配置

    "build:components": "npm run gen-version && node ./script/build.js"
    
const path = require('path')
const { defineConfig, build } = require('vite')
const vue = require('@vitejs/plugin-vue')
const vueJsx = require('@vitejs/plugin-vue-jsx')
const baseConfig = defineConfig({
  configFile: false,
  publicDir: false,
  plugins: [vue(), vueJsx()]
})
const entryFile = path.resolve(__dirname, './entry.ts')
const outputDir = path.resolve(__dirname, '../build')
const rollupOptions = {
  external: ['vue', 'vue-router'],
  output: {
    globals: {
      vue: 'Vue'
    }
  }
}
const buildAll = async () => {
  await build(
    defineConfig({
      ...baseConfig,
      build: {
        rollupOptions,
        lib: {
          entry: entryFile,
          name: 'mlysl-ui',
          fileName: 'mlysl-ui',
          formats: ['es', 'umd']
        },
        outDir: outputDir
      }
    })
  )
}
const buildLib = async () => {
  await buildAll()
}
buildLib()

2、设置入口文件(entry.ts)

3、入口中具名导出编写的所有组件

4、编写插件并导出(install)

// 引入实现的组件 批量导出
import type { App } from 'vue'
import ButtonPlugin, { Button } from '../src/button'

// 导出这些组件
export { Button }

const installs = [ButtonPlugin]
// 导出一个vue插件
export default {
  install(app: App) {
    installs.forEach(p => app.use(p))
  }
}

5、打包

yarn build:components

6、生成package.json

  • 手动添加

  • 打包中自动创建

二、按需打包

1、安装fs-extra库

2、在build.js中增加相关代码,以下是主要代码

3、rollup配置 设置格式

rollup 是一个 JavaScript 模块打包器,在功能上要完成的事和webpack性质一样,就是将小块代码编译成大块复杂的代码,例如 library 或应用程序。在平时开发应用程序时,我们基本上选择用webpack,相比之下,rollup.js更多是用于library打包,我们熟悉的vue、react、vuex、vue-router等都是用rollup进行打包的。

// 单组件按需构建
const buildSingle = async name => {
  await build(
    defineConfig({
      ...baseConfig,
      build: {
        rollupOptions,
        lib: {
          entry: path.resolve(componentsDir, name),
          name: 'index',
          fileName: 'index',
          formats: ['es', 'umd']
        },
        outDir: path.resolve(outputDir, name)
      }
    })
  )
  createPackageJson(name)
}
const buildLib = async () => {
  await buildAll()
  // 按需打包
  fs.readdirSync(componentsDir)// 读取目录
    .filter(name => {// 过滤名称
      // 只要目录不要文件,且里面包含index.ts
      const componentDir = path.resolve(componentsDir, name)
      const isDir = fs.lstatSync(componentDir).isDirectory()// 是不是路径
      return isDir && fs.readdirSync(componentDir).includes('index.ts')// 是路径且包含index
    })
    .forEach(async name => {
      // 打包单个目录
      await buildSingle(name)
    })
}
  • 更详细的代码参考github的源码

三、发布到npm

1、注册npm账号,去官网注册

2、修改registry

3、nom adduser添加用户,避免反复登录

4、登录npm login(第四步做了跳过)

5、npm publish ./build发布build目录

  • 再次发布的话改版本号打包

6、验证npm view mlysl-ui