vite-example-plugin.ts 1.82 KB
Newer Older
wanghao committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/* eslint-disable prefer-regex-literals */
import fs from "fs"
export default function examplePlugin(mode: string) {
  return {
    name: "transform-example",
    load(id: string) {
      // 填坑:在transform中处理的是编译后的文件内容,导致了一些bug
      if (id.endsWith(".tsx") || /widgets\/.*\/map.ts/.test(id)) {
        const data = fs.readFileSync(id)
        let source = data.toString()

        if (source.indexOf(`from "./map.js"`) !== -1) {
          // source = source.replace(/import \* as (\S*) from \"\.\/map\.js\"/g, "const $1 = window.mapWork")
          source = source.replace(/import \* as (\S*) from \"\.\/map\.js\"/g, "")
          source = source.replace(/ mapWork/g, " window.mapWork")
        }
        if (source.indexOf(`from "mars2d"`) !== -1) {
          source = source.replace(/import \* as (\S*) from \"mars2d\"/g, "const $1 = window.mars2d")
        }
        if (source.indexOf(`from "mars3d"`) !== -1) {
          source = source.replace(/import \* as (\S*) from \"mars3d\"/g, "const $1 = window.mars3d")
        }
        return source
      }
    },
    transform(source: string, id: string) {
      let code = source
      if (/example\/.*\/map.js/.test(id) && mode === "development") {
        // 替换let const
        code = code.replace(new RegExp("export let ", "gm"), "var ")
        code = code.replace(new RegExp("export const ", "gm"), "var ")

        // 浏览器中运行时,删除export import
        code = code.replace(new RegExp("export ", "gm"), "")
        code = code.replace(new RegExp("import ", "gm"), "// import ")

        // 删除const L = mars2d.L
        code = code.replace("const L = mars2d.L", "")
        // 删除const Cesium = mars3d.Cesium
        code = code.replace("const Cesium = mars3d.Cesium", "")
      }
      return {
        code
      }
    }
  }
}