| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 |
- /* eslint-disable no-undef */
- // 基座 SSO 静态资源注入插件
- //
- // 业务项目用法(vite.config.js):
- // import ssoPlugin from 'sapit-ui-plus/vite-plugins/sso-plugin.js'
- // plugins: [ssoPlugin()]
- //
- // dev:以中间件兜底提供 /sso.html 与 /js/sso.js|qs.js|jquery-3.6.0.min.js
- // (挂在 vite 内部中间件之后,业务项目 public/ 里的同名文件优先级更高)
- // build:构建结束把 sso.html 与 js/ 脚本写入产物根目录
- // (业务项目无需再在 public/ 里维护 sso 文件;lib 模式构建自动跳过)
- import fs from 'node:fs'
- import path from 'node:path'
- import crypto from 'node:crypto'
- import { fileURLToPath } from 'node:url'
- // 包内相对本插件的 sso 资源目录:<pkg>/sso/
- const defaultDir = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- 'sso'
- )
- // 相对 ssoDir 的文件 → Content-Type
- const FILES = {
- 'sso.html': 'text/html; charset=utf-8',
- 'js/sso.js': 'application/javascript; charset=utf-8',
- 'js/qs.js': 'application/javascript; charset=utf-8',
- 'js/jquery-3.6.0.min.js': 'application/javascript; charset=utf-8'
- }
- // 大 data URI 抽取阈值:超过则抽出为真实文件(lib 模式 vite 强制内联所有资产,
- // 大图 data URI 超浏览器 URL 长度上限无法渲染)
- const EXTRACT_THRESHOLD = 100 * 1024
- // 把产物 js/css 中超过阈值的 base64 data URI 抽出为 <outDir>/img/ 下的真实文件,
- // 并把引用改为相对当前文件的运行时路径(js 用 new URL(...,import.meta.url),css 直接相对路径)
- function extractLargeInlineAssets (outDir) {
- const imgDir = path.join(outDir, 'img')
- const scanDir = (dir, exts) => {
- let files = []
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
- const full = path.join(dir, entry.name)
- if (entry.isDirectory()) files = files.concat(scanDir(full, exts))
- else if (exts.some((e) => entry.name.endsWith(e))) files.push(full)
- }
- return files
- }
- const files = scanDir(outDir, ['.js', '.css'])
- let extracted = 0
- for (const file of files) {
- const isCss = file.endsWith('.css')
- let code = fs.readFileSync(file, 'utf8')
- let changed = false
- // 形态一:new URL("data:...;base64,xxx", import.meta.url) —— 只替换内部字面量为相对路径
- code = code.replace(
- /new URL\((['"])(data:image\/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=]+))\1, ?import\.meta\.url\)/g,
- (m, q, uri, sub, payload) => {
- if (uri.length < EXTRACT_THRESHOLD) return m
- const info = writeAsset(imgDir, outDir, sub, payload, file)
- extracted++
- changed = true
- return `new URL(${q}${info}${q}, import.meta.url)`
- }
- )
- // 形态二:普通字符串常量(lib 模式 import 内联的产物)—— 整体替换为 new URL 表达式
- code = code.replace(
- /(['"])(data:image\/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=]+))\1/g,
- (m, q, uri, sub, payload) => {
- if (uri.length < EXTRACT_THRESHOLD) return m
- const info = writeAsset(imgDir, outDir, sub, payload, file)
- extracted++
- changed = true
- if (isCss) return `url(${info})`
- return `new URL(${q}${info}${q}, import.meta.url).href`
- }
- )
- if (changed) fs.writeFileSync(file, code)
- }
- if (extracted) console.log(`[sapit-sso-assets] 已抽取 ${extracted} 个大内联资产到 img/`)
- }
- function writeAsset (imgDir, outDir, sub, payload, refFile) {
- fs.mkdirSync(imgDir, { recursive: true })
- const buf = Buffer.from(payload, 'base64')
- const hash = crypto.createHash('md5').update(buf).digest('hex').slice(0, 10)
- const ext = sub === 'jpeg' ? 'jpg' : sub
- const name = `inline-${hash}.${ext}`
- fs.writeFileSync(path.join(imgDir, name), buf)
- return path.relative(path.dirname(refFile), path.join(imgDir, name)).split(path.sep).join('/')
- }
- export default function ssoPlugin (options = {}) {
- const ssoDir = options.dir || defaultDir
- let root = process.cwd()
- let outDir = 'dist'
- let base = '/'
- let isLibBuild = false
- return {
- name: 'sapit-sso-assets',
- // 业务项目 dev 不预打包基座库:预打包会把资产统一内联成 data URI,
- // 大图超浏览器 URL 上限必挂;排除后直读原始模块(资产为真实文件引用)
- config () {
- return { optimizeDeps: { exclude: ['sapit-ui-plus'] } }
- },
- configResolved (config) {
- root = config.root || process.cwd()
- base = config.base || '/'
- outDir = (config.build && config.build.outDir) || 'dist'
- // 基座 lib 模式构建(打包组件库)不注入静态页
- isLibBuild = !!(config.build && config.build.lib)
- },
- // dev 防护:lib 产物里剩余的 `new URL("data:...", import.meta.url)`(如 utils.getImg
- // 动态调用产生的)会被 vite 的 import.meta.url 资产插件当相对路径解析,URL 规范化
- // 会吞掉 data URI 内容里的 "//"(xmlns、base64 全被破坏)。把字符串字面量拆成
- // 拼接表达式,让该插件的正则匹配不到;运行时求值结果不变。
- enforce: 'pre',
- transform (code) {
- if (code.indexOf('new URL("data:') === -1 && code.indexOf("new URL('data:") === -1) {
- return null
- }
- const RE = /new URL\((['"])data:[\s\S]*?\1, ?import\.meta\.url\)/g
- if (!RE.test(code)) return null
- return {
- code: code.replace(RE, (m) => m.replace(/, ?import\.meta\.url\)$/, ' + "", import.meta.url)')),
- map: null
- }
- },
- configureServer (server) {
- // post hook:在 vite 内部中间件之后执行,public/ 同名文件优先生效
- server.middlewares.use((req, res, next) => {
- let url = (req.url || '').split('?')[0]
- try { url = decodeURIComponent(url) } catch (e) { /* 保持原值 */ }
- if (base && base !== '/' && url.indexOf(base) === 0) {
- url = '/' + url.slice(base.length)
- }
- const contentType = FILES[url.replace(/^\//, '')]
- if (!contentType) return next()
- const full = path.join(ssoDir, url)
- if (!fs.existsSync(full)) return next()
- res.setHeader('Content-Type', contentType)
- res.end(fs.readFileSync(full))
- })
- },
- closeBundle () {
- const target = path.isAbsolute(outDir) ? outDir : path.join(root, outDir)
- if (isLibBuild) {
- // lib 模式 vite 强制内联所有资产(shouldInline 首行 config.build.lib 直接 return true,
- // assetsInlineLimit/?url 均无效),大图 data URI 超浏览器 URL 上限无法渲染,
- // 构建后统一抽出为真实文件
- extractLargeInlineAssets(target)
- return
- }
- for (const rel of Object.keys(FILES)) {
- const src = path.join(ssoDir, rel)
- const dest = path.join(target, rel)
- if (!fs.existsSync(src)) continue
- fs.mkdirSync(path.dirname(dest), { recursive: true })
- fs.copyFileSync(src, dest)
- }
- console.log(`[sapit-sso-assets] sso.html 与 js 脚本已注入 ${target}`)
- }
- }
- }
|