Skip to content

Commit 3c2f6b9

Browse files
author
Adam Hines
committed
fix(treeshaking): allowing treeshaking in terser
The code currently generated by this plugin looks something like the following when building a library: src/index.js ```js export {default as Foo} from './component.vue'; ``` ```js var __component__ = /*#__PURE__*/ normalizeComponent(...) var Foo = __component__.exports ``` In the event you aren't actually using the Foo export, this code is unable to be dropped because Terser assumes that property access (__component__.exports) is not side-effect free and as a result it decides it can not drop it, and thus it can't drop the rest of the component code. To work around this, I have wrapped the `__component__.exports` statement in a function so that we can mark the function invokation as `#__PURE__` and thus allow for unused components to be dropped fully. The resulting code looks like: ```js var __component__ = /*#__PURE__*/ normalizeComponent(...) var Foo = /*#__PURE__*/ getExports(__component__) ```
1 parent ad7d61e commit 3c2f6b9

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

src/main.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export async function transformMain(
7474

7575
output.push(
7676
`/* normalize component */
77-
import __normalizer from "${NORMALIZER_ID}"
77+
import {normalizeComponent as __normalizer, getExports as __getExports} from "${NORMALIZER_ID}"
7878
var __component__ = /*#__PURE__*/__normalizer(
7979
_sfc_main,
8080
_sfc_render,
@@ -137,7 +137,7 @@ var __component__ = /*#__PURE__*/__normalizer(
137137

138138
let resolvedMap: RawSourceMap | undefined = scriptMap
139139

140-
output.push(`export default __component__.exports`)
140+
output.push(`export default /*#__PURE__*/ __getExports(__component__)`)
141141

142142
// handle TS transpilation
143143
let resolvedCode = output.join('\n')

src/utils/componentNormalizer.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@ export const NORMALIZER_ID = '\0plugin-vue2:normalizer'
44
// This module is a runtime utility for cleaner component module output and will
55
// be included in the final webpack user bundle.
66
export const normalizerCode = `
7-
export default function normalizeComponent (
7+
// Used to facilitate tree-shaking since property access is not guaranteed to be pure
8+
export function getExports(component) {
9+
return component.exports
10+
}
11+
12+
export function normalizeComponent (
813
scriptExports,
914
render,
1015
staticRenderFns,

0 commit comments

Comments
 (0)