You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

377 lines
11 KiB

  1. // @ts-check
  2. import assert from 'node:assert/strict'
  3. import { createRequire } from 'node:module'
  4. import { fileURLToPath } from 'node:url'
  5. import path from 'node:path'
  6. import replace from '@rollup/plugin-replace'
  7. import json from '@rollup/plugin-json'
  8. import pico from 'picocolors'
  9. import commonJS from '@rollup/plugin-commonjs'
  10. import polyfillNode from 'rollup-plugin-polyfill-node'
  11. import { nodeResolve } from '@rollup/plugin-node-resolve'
  12. import terser from '@rollup/plugin-terser'
  13. import esbuild from 'rollup-plugin-esbuild'
  14. import alias from '@rollup/plugin-alias'
  15. import { entries } from './scripts/aliases.js'
  16. import { inlineEnums } from './scripts/inline-enums.js'
  17. /**
  18. * @template T
  19. * @template {keyof T} K
  20. * @typedef { Omit<T, K> & Required<Pick<T, K>> } MarkRequired
  21. */
  22. /** @typedef {'cjs' | 'esm-bundler' | 'global' | 'global-runtime' | 'esm-browser' | 'esm-bundler-runtime' | 'esm-browser-runtime'} PackageFormat */
  23. /** @typedef {MarkRequired<import('rollup').OutputOptions, 'file' | 'format'>} OutputOptions */
  24. if (!process.env.TARGET) {
  25. throw new Error('TARGET package must be specified via --environment flag.')
  26. }
  27. const require = createRequire(import.meta.url)
  28. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  29. const masterVersion = require('./package.json').version
  30. const consolidatePkg = require('@vue/consolidate/package.json')
  31. const packagesDir = path.resolve(__dirname, 'packages')
  32. const packageDir = path.resolve(packagesDir, process.env.TARGET)
  33. const resolve = (/** @type {string} */ p) => path.resolve(packageDir, p)
  34. const pkg = require(resolve(`package.json`))
  35. const packageOptions = pkg.buildOptions || {}
  36. const name = packageOptions.filename || path.basename(packageDir)
  37. const [enumPlugin, enumDefines] = inlineEnums()
  38. /** @type {Record<PackageFormat, OutputOptions>} */
  39. const outputConfigs = {
  40. 'esm-bundler': {
  41. file: resolve(`dist/${name}.esm-bundler.js`),
  42. format: 'es',
  43. },
  44. 'esm-browser': {
  45. file: resolve(`dist/${name}.esm-browser.js`),
  46. format: 'es',
  47. },
  48. cjs: {
  49. file: resolve(`dist/${name}.cjs.js`),
  50. format: 'cjs',
  51. },
  52. global: {
  53. file: resolve(`dist/${name}.global.js`),
  54. format: 'iife',
  55. },
  56. // runtime-only builds, for main "vue" package only
  57. 'esm-bundler-runtime': {
  58. file: resolve(`dist/${name}.runtime.esm-bundler.js`),
  59. format: 'es',
  60. },
  61. 'esm-browser-runtime': {
  62. file: resolve(`dist/${name}.runtime.esm-browser.js`),
  63. format: 'es',
  64. },
  65. 'global-runtime': {
  66. file: resolve(`dist/${name}.runtime.global.js`),
  67. format: 'iife',
  68. },
  69. }
  70. /** @type {ReadonlyArray<PackageFormat>} */
  71. const defaultFormats = ['esm-bundler', 'cjs']
  72. /** @type {ReadonlyArray<PackageFormat>} */
  73. const inlineFormats = /** @type {any} */ (
  74. process.env.FORMATS && process.env.FORMATS.split(',')
  75. )
  76. /** @type {ReadonlyArray<PackageFormat>} */
  77. const packageFormats = inlineFormats || packageOptions.formats || defaultFormats
  78. const packageConfigs = process.env.PROD_ONLY
  79. ? []
  80. : packageFormats.map(format => createConfig(format, outputConfigs[format]))
  81. if (process.env.NODE_ENV === 'production') {
  82. packageFormats.forEach(format => {
  83. if (packageOptions.prod === false) {
  84. return
  85. }
  86. if (format === 'cjs') {
  87. packageConfigs.push(createProductionConfig(format))
  88. }
  89. if (/^(global|esm-browser)(-runtime)?/.test(format)) {
  90. packageConfigs.push(createMinifiedConfig(format))
  91. }
  92. })
  93. }
  94. export default packageConfigs
  95. /**
  96. *
  97. * @param {PackageFormat} format
  98. * @param {OutputOptions} output
  99. * @param {ReadonlyArray<import('rollup').Plugin>} plugins
  100. * @returns {import('rollup').RollupOptions}
  101. */
  102. function createConfig(format, output, plugins = []) {
  103. if (!output) {
  104. console.log(pico.yellow(`invalid format: "${format}"`))
  105. process.exit(1)
  106. }
  107. const isProductionBuild =
  108. process.env.__DEV__ === 'false' || /\.prod\.js$/.test(output.file)
  109. const isBundlerESMBuild = /esm-bundler/.test(format)
  110. const isBrowserESMBuild = /esm-browser/.test(format)
  111. const isServerRenderer = name === 'server-renderer'
  112. const isCJSBuild = format === 'cjs'
  113. const isGlobalBuild = /global/.test(format)
  114. const isCompatPackage =
  115. pkg.name === '@vue/compat' || pkg.name === '@vue/compat-canary'
  116. const isCompatBuild = !!packageOptions.compat
  117. const isBrowserBuild =
  118. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  119. !packageOptions.enableNonBrowserBranches
  120. output.banner = `/**
  121. * ${pkg.name} v${masterVersion}
  122. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  123. * @license MIT
  124. **/`
  125. output.exports = isCompatPackage ? 'auto' : 'named'
  126. if (isCJSBuild) {
  127. output.esModule = true
  128. }
  129. output.sourcemap = !!process.env.SOURCE_MAP
  130. output.externalLiveBindings = false
  131. // https://github.com/rollup/rollup/pull/5380
  132. output.reexportProtoFromExternal = false
  133. if (isGlobalBuild) {
  134. output.name = packageOptions.name
  135. }
  136. let entryFile = /runtime$/.test(format) ? `src/runtime.ts` : `src/index.ts`
  137. // the compat build needs both default AND named exports. This will cause
  138. // Rollup to complain for non-ESM targets, so we use separate entries for
  139. // esm vs. non-esm builds.
  140. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  141. entryFile = /runtime$/.test(format)
  142. ? `src/esm-runtime.ts`
  143. : `src/esm-index.ts`
  144. }
  145. function resolveDefine() {
  146. /** @type {Record<string, string>} */
  147. const replacements = {
  148. __COMMIT__: `"${process.env.COMMIT}"`,
  149. __VERSION__: `"${masterVersion}"`,
  150. // this is only used during Vue's internal tests
  151. __TEST__: `false`,
  152. // If the build is expected to run directly in the browser (global / esm builds)
  153. __BROWSER__: String(isBrowserBuild),
  154. __GLOBAL__: String(isGlobalBuild),
  155. __ESM_BUNDLER__: String(isBundlerESMBuild),
  156. __ESM_BROWSER__: String(isBrowserESMBuild),
  157. // is targeting Node (SSR)?
  158. __CJS__: String(isCJSBuild),
  159. // need SSR-specific branches?
  160. __SSR__: String(isCJSBuild || isBundlerESMBuild || isServerRenderer),
  161. // 2.x compat build
  162. __COMPAT__: String(isCompatBuild),
  163. // feature flags
  164. __FEATURE_SUSPENSE__: `true`,
  165. __FEATURE_OPTIONS_API__: isBundlerESMBuild
  166. ? `__VUE_OPTIONS_API__`
  167. : `true`,
  168. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  169. ? `__VUE_PROD_DEVTOOLS__`
  170. : `false`,
  171. __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: isBundlerESMBuild
  172. ? `__VUE_PROD_HYDRATION_MISMATCH_DETAILS__`
  173. : `false`,
  174. }
  175. if (!isBundlerESMBuild) {
  176. // hard coded dev/prod builds
  177. replacements.__DEV__ = String(!isProductionBuild)
  178. }
  179. // allow inline overrides like
  180. //__RUNTIME_COMPILE__=true pnpm build runtime-core
  181. Object.keys(replacements).forEach(key => {
  182. if (key in process.env) {
  183. const value = process.env[key]
  184. assert(typeof value === 'string')
  185. replacements[key] = value
  186. }
  187. })
  188. return replacements
  189. }
  190. // esbuild define is a bit strict and only allows literal json or identifiers
  191. // so we still need replace plugin in some cases
  192. function resolveReplace() {
  193. const replacements = { ...enumDefines }
  194. if (isProductionBuild && isBrowserBuild) {
  195. Object.assign(replacements, {
  196. 'context.onError(': `/*#__PURE__*/ context.onError(`,
  197. 'emitError(': `/*#__PURE__*/ emitError(`,
  198. 'createCompilerError(': `/*#__PURE__*/ createCompilerError(`,
  199. 'createDOMCompilerError(': `/*#__PURE__*/ createDOMCompilerError(`,
  200. })
  201. }
  202. if (isBundlerESMBuild) {
  203. Object.assign(replacements, {
  204. // preserve to be handled by bundlers
  205. __DEV__: `!!(process.env.NODE_ENV !== 'production')`,
  206. })
  207. }
  208. // for compiler-sfc browser build inlined deps
  209. if (isBrowserESMBuild) {
  210. Object.assign(replacements, {
  211. 'process.env': '({})',
  212. 'process.platform': '""',
  213. 'process.stdout': 'null',
  214. })
  215. }
  216. if (Object.keys(replacements).length) {
  217. return [replace({ values: replacements, preventAssignment: true })]
  218. } else {
  219. return []
  220. }
  221. }
  222. function resolveExternal() {
  223. const treeShakenDeps = [
  224. 'source-map-js',
  225. '@babel/parser',
  226. 'estree-walker',
  227. 'entities/lib/decode.js',
  228. ]
  229. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  230. if (!packageOptions.enableNonBrowserBranches) {
  231. // normal browser builds - non-browser only imports are tree-shaken,
  232. // they are only listed here to suppress warnings.
  233. return treeShakenDeps
  234. }
  235. } else {
  236. // Node / esm-bundler builds.
  237. // externalize all direct deps unless it's the compat build.
  238. return [
  239. ...Object.keys(pkg.dependencies || {}),
  240. ...Object.keys(pkg.peerDependencies || {}),
  241. // for @vue/compiler-sfc / server-renderer
  242. ...['path', 'url', 'stream'],
  243. // somehow these throw warnings for runtime-* package builds
  244. ...treeShakenDeps,
  245. ]
  246. }
  247. }
  248. function resolveNodePlugins() {
  249. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  250. // requires a ton of template engines which should be ignored.
  251. /** @type {ReadonlyArray<string>} */
  252. let cjsIgnores = []
  253. if (
  254. pkg.name === '@vue/compiler-sfc' ||
  255. pkg.name === '@vue/compiler-sfc-canary'
  256. ) {
  257. cjsIgnores = [
  258. ...Object.keys(consolidatePkg.devDependencies),
  259. 'vm',
  260. 'crypto',
  261. 'react-dom/server',
  262. 'teacup/lib/express',
  263. 'arc-templates/dist/es5',
  264. 'then-pug',
  265. 'then-jade',
  266. ]
  267. }
  268. const nodePlugins =
  269. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  270. packageOptions.enableNonBrowserBranches
  271. ? [
  272. commonJS({
  273. sourceMap: false,
  274. ignore: cjsIgnores,
  275. }),
  276. ...(format === 'cjs' ? [] : [polyfillNode()]),
  277. nodeResolve(),
  278. ]
  279. : []
  280. return nodePlugins
  281. }
  282. return {
  283. input: resolve(entryFile),
  284. // Global and Browser ESM builds inlines everything so that they can be
  285. // used alone.
  286. external: resolveExternal(),
  287. plugins: [
  288. json({
  289. namedExports: false,
  290. }),
  291. alias({
  292. entries,
  293. }),
  294. enumPlugin,
  295. ...resolveReplace(),
  296. esbuild({
  297. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  298. sourceMap: output.sourcemap,
  299. minify: false,
  300. target: isServerRenderer || isCJSBuild ? 'es2019' : 'es2015',
  301. define: resolveDefine(),
  302. }),
  303. ...resolveNodePlugins(),
  304. ...plugins,
  305. ],
  306. output,
  307. onwarn: (msg, warn) => {
  308. if (msg.code !== 'CIRCULAR_DEPENDENCY') {
  309. warn(msg)
  310. }
  311. },
  312. treeshake: {
  313. moduleSideEffects: false,
  314. },
  315. }
  316. }
  317. function createProductionConfig(/** @type {PackageFormat} */ format) {
  318. return createConfig(format, {
  319. file: resolve(`dist/${name}.${format}.prod.js`),
  320. format: outputConfigs[format].format,
  321. })
  322. }
  323. function createMinifiedConfig(/** @type {PackageFormat} */ format) {
  324. return createConfig(
  325. format,
  326. {
  327. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  328. format: outputConfigs[format].format,
  329. },
  330. [
  331. terser({
  332. module: /^esm/.test(format),
  333. compress: {
  334. ecma: 2015,
  335. pure_getters: true,
  336. },
  337. safari10: true,
  338. }),
  339. ],
  340. )
  341. }