rollup.config.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. import { defineConfig, Plugin, RollupLog } from 'rollup'
  5. import typescript from '@rollup/plugin-typescript'
  6. import terser from '@rollup/plugin-terser'
  7. import fg from 'fast-glob'
  8. import { basename, join } from 'path'
  9. import { copyFileSync, opendirSync, rmSync, Dir } from 'fs'
  10. import { fileURLToPath } from 'url'
  11. // cleanup dist dir
  12. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  13. cleanDir(join(__dirname, './dist'))
  14. const modules = fg.sync(['./src/*.ts'])
  15. export default defineConfig([
  16. {
  17. input: Object.fromEntries(modules.map((p) => [basename(p, '.ts'), p])),
  18. output: [
  19. {
  20. format: 'esm',
  21. dir: './dist',
  22. preserveModules: true,
  23. preserveModulesRoot: 'src',
  24. entryFileNames: '[name].js'
  25. },
  26. {
  27. format: 'cjs',
  28. dir: './dist',
  29. preserveModules: true,
  30. preserveModulesRoot: 'src',
  31. entryFileNames: '[name].cjs'
  32. }
  33. ],
  34. plugins: [
  35. typescript({
  36. declaration: true,
  37. declarationDir: './dist',
  38. rootDir: 'src'
  39. }),
  40. makeFlatPackageInDist()
  41. ],
  42. onwarn
  43. },
  44. {
  45. input: 'src/index.ts',
  46. output: {
  47. format: 'iife',
  48. name: '__TAURI_IIFE__',
  49. footer: 'window.__TAURI__ = __TAURI_IIFE__',
  50. file: '../../core/tauri/scripts/bundle.global.js'
  51. },
  52. plugins: [typescript(), terser()],
  53. onwarn
  54. }
  55. ])
  56. function onwarn(warning: RollupLog) {
  57. // deny warnings by default
  58. throw Object.assign(new Error(), warning)
  59. }
  60. function makeFlatPackageInDist(): Plugin {
  61. return {
  62. name: 'makeFlatPackageInDist',
  63. writeBundle() {
  64. // copy necessary files like `CHANGELOG.md` , `README.md` and Licenses to `./dist`
  65. fg.sync('(LICENSE*|*.md|package.json)').forEach((f) =>
  66. copyFileSync(f, `dist/${f}`)
  67. )
  68. }
  69. }
  70. }
  71. function cleanDir(path: string) {
  72. let dir: Dir
  73. try {
  74. dir = opendirSync(path)
  75. } catch (err: any) {
  76. switch (err.code) {
  77. case 'ENOENT':
  78. return // Noop when directory don't exists.
  79. case 'ENOTDIR':
  80. throw new Error(`'${path}' is not a directory.`)
  81. default:
  82. throw err
  83. }
  84. }
  85. let file = dir.readSync()
  86. while (file) {
  87. const filePath = join(path, file.name)
  88. rmSync(filePath, { recursive: true })
  89. file = dir.readSync()
  90. }
  91. dir.closeSync()
  92. }