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.

381 lines
12 KiB

  1. // @ts-check
  2. import { createRequire } from 'module'
  3. import { fileURLToPath } from 'url'
  4. import path from 'path'
  5. import ts from 'rollup-plugin-typescript2'
  6. import replace from '@rollup/plugin-replace'
  7. import json from '@rollup/plugin-json'
  8. import chalk from 'chalk'
  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. if (!process.env.TARGET) {
  14. throw new Error('TARGET package must be specified via --environment flag.')
  15. }
  16. const require = createRequire(import.meta.url)
  17. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  18. const masterVersion = require('./package.json').version
  19. const consolidatePkg = require('@vue/consolidate/package.json')
  20. const packagesDir = path.resolve(__dirname, 'packages')
  21. const packageDir = path.resolve(packagesDir, process.env.TARGET)
  22. const resolve = p => path.resolve(packageDir, p)
  23. const pkg = require(resolve(`package.json`))
  24. const packageOptions = pkg.buildOptions || {}
  25. const name = packageOptions.filename || path.basename(packageDir)
  26. // ensure TS checks only once for each build
  27. let hasTSChecked = false
  28. const outputConfigs = {
  29. 'esm-bundler': {
  30. file: resolve(`dist/${name}.esm-bundler.js`),
  31. format: `es`
  32. },
  33. 'esm-browser': {
  34. file: resolve(`dist/${name}.esm-browser.js`),
  35. format: `es`
  36. },
  37. cjs: {
  38. file: resolve(`dist/${name}.cjs.js`),
  39. format: `cjs`
  40. },
  41. global: {
  42. file: resolve(`dist/${name}.global.js`),
  43. format: `iife`
  44. },
  45. // runtime-only builds, for main "vue" package only
  46. 'esm-bundler-runtime': {
  47. file: resolve(`dist/${name}.runtime.esm-bundler.js`),
  48. format: `es`
  49. },
  50. 'esm-browser-runtime': {
  51. file: resolve(`dist/${name}.runtime.esm-browser.js`),
  52. format: 'es'
  53. },
  54. 'global-runtime': {
  55. file: resolve(`dist/${name}.runtime.global.js`),
  56. format: 'iife'
  57. }
  58. }
  59. const defaultFormats = ['esm-bundler', 'cjs']
  60. const inlineFormats = process.env.FORMATS && process.env.FORMATS.split(',')
  61. const packageFormats = inlineFormats || packageOptions.formats || defaultFormats
  62. const packageConfigs = process.env.PROD_ONLY
  63. ? []
  64. : packageFormats.map(format => createConfig(format, outputConfigs[format]))
  65. if (process.env.NODE_ENV === 'production') {
  66. packageFormats.forEach(format => {
  67. if (packageOptions.prod === false) {
  68. return
  69. }
  70. if (format === 'cjs') {
  71. packageConfigs.push(createProductionConfig(format))
  72. }
  73. if (/^(global|esm-browser)(-runtime)?/.test(format)) {
  74. packageConfigs.push(createMinifiedConfig(format))
  75. }
  76. })
  77. }
  78. export default packageConfigs
  79. function createConfig(format, output, plugins = []) {
  80. if (!output) {
  81. console.log(chalk.yellow(`invalid format: "${format}"`))
  82. process.exit(1)
  83. }
  84. const isProductionBuild =
  85. process.env.__DEV__ === 'false' || /\.prod\.js$/.test(output.file)
  86. const isBundlerESMBuild = /esm-bundler/.test(format)
  87. const isBrowserESMBuild = /esm-browser/.test(format)
  88. const isServerRenderer = name === 'server-renderer'
  89. const isNodeBuild = format === 'cjs'
  90. const isGlobalBuild = /global/.test(format)
  91. const isCompatPackage = pkg.name === '@vue/compat'
  92. const isCompatBuild = !!packageOptions.compat
  93. output.exports = isCompatPackage ? 'auto' : 'named'
  94. if (isNodeBuild) {
  95. output.esModule = true
  96. }
  97. output.sourcemap = !!process.env.SOURCE_MAP
  98. output.externalLiveBindings = false
  99. if (isGlobalBuild) {
  100. output.name = packageOptions.name
  101. }
  102. const shouldEmitDeclarations =
  103. pkg.types && process.env.TYPES != null && !hasTSChecked
  104. const tsPlugin = ts({
  105. check: process.env.NODE_ENV === 'production' && !hasTSChecked,
  106. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  107. cacheRoot: path.resolve(__dirname, 'node_modules/.rts2_cache'),
  108. tsconfigOverride: {
  109. compilerOptions: {
  110. target: isServerRenderer || isNodeBuild ? 'es2019' : 'es2015',
  111. sourceMap: output.sourcemap,
  112. declaration: shouldEmitDeclarations,
  113. declarationMap: shouldEmitDeclarations
  114. },
  115. exclude: ['**/__tests__', 'test-dts']
  116. }
  117. })
  118. // we only need to check TS and generate declarations once for each build.
  119. // it also seems to run into weird issues when checking multiple times
  120. // during a single build.
  121. hasTSChecked = true
  122. let entryFile = /runtime$/.test(format) ? `src/runtime.ts` : `src/index.ts`
  123. // the compat build needs both default AND named exports. This will cause
  124. // Rollup to complain for non-ESM targets, so we use separate entries for
  125. // esm vs. non-esm builds.
  126. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  127. entryFile = /runtime$/.test(format)
  128. ? `src/esm-runtime.ts`
  129. : `src/esm-index.ts`
  130. }
  131. let external = []
  132. const treeShakenDeps = ['source-map', '@babel/parser', 'estree-walker']
  133. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  134. if (!packageOptions.enableNonBrowserBranches) {
  135. // normal browser builds - non-browser only imports are tree-shaken,
  136. // they are only listed here to suppress warnings.
  137. external = treeShakenDeps
  138. }
  139. } else {
  140. // Node / esm-bundler builds.
  141. // externalize all direct deps unless it's the compat build.
  142. external = [
  143. ...Object.keys(pkg.dependencies || {}),
  144. ...Object.keys(pkg.peerDependencies || {}),
  145. // for @vue/compiler-sfc / server-renderer
  146. ...['path', 'url', 'stream'],
  147. // somehow these throw warnings for runtime-* package builds
  148. ...treeShakenDeps
  149. ]
  150. }
  151. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  152. // requires a ton of template engines which should be ignored.
  153. let cjsIgnores = []
  154. if (pkg.name === '@vue/compiler-sfc') {
  155. cjsIgnores = [
  156. ...Object.keys(consolidatePkg.devDependencies),
  157. 'vm',
  158. 'crypto',
  159. 'react-dom/server',
  160. 'teacup/lib/express',
  161. 'arc-templates/dist/es5',
  162. 'then-pug',
  163. 'then-jade'
  164. ]
  165. }
  166. const nodePlugins =
  167. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  168. packageOptions.enableNonBrowserBranches
  169. ? [
  170. commonJS({
  171. sourceMap: false,
  172. ignore: cjsIgnores
  173. }),
  174. ...(format === 'cjs' ? [] : [polyfillNode()]),
  175. nodeResolve()
  176. ]
  177. : []
  178. if (format === 'cjs') {
  179. nodePlugins.push(cjsReExportsPatchPlugin())
  180. }
  181. return {
  182. input: resolve(entryFile),
  183. // Global and Browser ESM builds inlines everything so that they can be
  184. // used alone.
  185. external,
  186. plugins: [
  187. json({
  188. namedExports: false
  189. }),
  190. tsPlugin,
  191. createReplacePlugin(
  192. isProductionBuild,
  193. isBundlerESMBuild,
  194. isBrowserESMBuild,
  195. // isBrowserBuild?
  196. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  197. !packageOptions.enableNonBrowserBranches,
  198. isGlobalBuild,
  199. isNodeBuild,
  200. isCompatBuild,
  201. isServerRenderer
  202. ),
  203. ...nodePlugins,
  204. ...plugins
  205. ],
  206. output,
  207. onwarn: (msg, warn) => {
  208. if (!/Circular/.test(msg)) {
  209. warn(msg)
  210. }
  211. },
  212. treeshake: {
  213. moduleSideEffects: false
  214. }
  215. }
  216. }
  217. function createReplacePlugin(
  218. isProduction,
  219. isBundlerESMBuild,
  220. isBrowserESMBuild,
  221. isBrowserBuild,
  222. isGlobalBuild,
  223. isNodeBuild,
  224. isCompatBuild,
  225. isServerRenderer
  226. ) {
  227. const replacements = {
  228. __COMMIT__: `"${process.env.COMMIT}"`,
  229. __VERSION__: `"${masterVersion}"`,
  230. __DEV__: isBundlerESMBuild
  231. ? // preserve to be handled by bundlers
  232. `(process.env.NODE_ENV !== 'production')`
  233. : // hard coded dev/prod builds
  234. !isProduction,
  235. // this is only used during Vue's internal tests
  236. __TEST__: false,
  237. // If the build is expected to run directly in the browser (global / esm builds)
  238. __BROWSER__: isBrowserBuild,
  239. __GLOBAL__: isGlobalBuild,
  240. __ESM_BUNDLER__: isBundlerESMBuild,
  241. __ESM_BROWSER__: isBrowserESMBuild,
  242. // is targeting Node (SSR)?
  243. __NODE_JS__: isNodeBuild,
  244. // need SSR-specific branches?
  245. __SSR__: isNodeBuild || isBundlerESMBuild || isServerRenderer,
  246. // for compiler-sfc browser build inlined deps
  247. ...(isBrowserESMBuild
  248. ? {
  249. 'process.env': '({})',
  250. 'process.platform': '""',
  251. 'process.stdout': 'null'
  252. }
  253. : {}),
  254. // 2.x compat build
  255. __COMPAT__: isCompatBuild,
  256. // feature flags
  257. __FEATURE_SUSPENSE__: true,
  258. __FEATURE_OPTIONS_API__: isBundlerESMBuild ? `__VUE_OPTIONS_API__` : true,
  259. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  260. ? `__VUE_PROD_DEVTOOLS__`
  261. : false,
  262. ...(isProduction && isBrowserBuild
  263. ? {
  264. 'context.onError(': `/*#__PURE__*/ context.onError(`,
  265. 'emitError(': `/*#__PURE__*/ emitError(`,
  266. 'createCompilerError(': `/*#__PURE__*/ createCompilerError(`,
  267. 'createDOMCompilerError(': `/*#__PURE__*/ createDOMCompilerError(`
  268. }
  269. : {})
  270. }
  271. // allow inline overrides like
  272. //__RUNTIME_COMPILE__=true yarn build runtime-core
  273. Object.keys(replacements).forEach(key => {
  274. if (key in process.env) {
  275. replacements[key] = process.env[key]
  276. }
  277. })
  278. return replace({
  279. // @ts-ignore
  280. values: replacements,
  281. preventAssignment: true
  282. })
  283. }
  284. function createProductionConfig(format) {
  285. return createConfig(format, {
  286. file: resolve(`dist/${name}.${format}.prod.js`),
  287. format: outputConfigs[format].format
  288. })
  289. }
  290. function createMinifiedConfig(format) {
  291. return createConfig(
  292. format,
  293. {
  294. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  295. format: outputConfigs[format].format
  296. },
  297. [
  298. terser({
  299. module: /^esm/.test(format),
  300. compress: {
  301. ecma: 2015,
  302. pure_getters: true
  303. },
  304. safari10: true
  305. })
  306. ]
  307. )
  308. }
  309. // temporary patch for https://github.com/nodejs/cjs-module-lexer/issues/79
  310. //
  311. // When importing a cjs module from esm, Node.js uses cjs-module-lexer to
  312. // detect * re-exports from other packages. However, the detection logic is
  313. // fragile and breaks when Rollup generates different code for the re-exports.
  314. // We were locked on an old version of Rollup because of this.
  315. //
  316. // The latest versions of Node ships an updated version of cjs-module-lexer that
  317. // has fixed https://github.com/nodejs/cjs-module-lexer/issues/38, however we
  318. // still need to support older versions of Node that does not have the latest
  319. // version of cjs-module-lexer (Node < 14.18)
  320. //
  321. // At the same time, we want to upgrade to Rollup 3 so we are not forever locked
  322. // on an old version of Rollup.
  323. //
  324. // What this patch does:
  325. // 1. Rewrite the for...in loop to Object.keys() so cjs-module-lexer can find it
  326. // The for...in loop is only used when output.externalLiveBindings is set to
  327. // false, and we do want to set it to false to avoid perf costs during SSR.
  328. // 2. Also remove exports.hasOwnProperty check, which breaks the detection in
  329. // Node.js versions that
  330. //
  331. // TODO in the future, we should no longer rely on this if we inline all deps
  332. // in the main `vue` package.
  333. function cjsReExportsPatchPlugin() {
  334. const matcher =
  335. /for \(var k in (\w+)\) {(\s+if \(k !== 'default') && !exports.hasOwnProperty\(k\)(\) exports\[k\] = (?:\w+)\[k\];\s+)}/
  336. return {
  337. name: 'patch-cjs-re-exports',
  338. renderChunk(code, _, options) {
  339. if (matcher.test(code)) {
  340. return code.replace(matcher, (_, r1, r2, r3) => {
  341. return `Object.keys(${r1}).forEach(function(k) {${r2}${r3}});`
  342. })
  343. } else if (options.file.endsWith('packages/vue/dist/vue.cjs.js')) {
  344. // make sure we don't accidentally miss the rewrite in case Rollup
  345. // changes the output again.
  346. throw new Error('cjs build re-exports rewrite failed.')
  347. }
  348. }
  349. }
  350. }