Skip to content

Commit

Permalink
fix(treeshaking): allowing treeshaking in terser
Browse files Browse the repository at this point in the history
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, using a minifier like Terser, 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 components.

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__)
```
  • Loading branch information
Adam Hines committed Jan 12, 2023
1 parent ad7d61e commit 2f53050
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export async function transformMain(

output.push(
`/* normalize component */
import __normalizer from "${NORMALIZER_ID}"
import {normalizeComponent as __normalizer, getExports as __getExports} from "${NORMALIZER_ID}"
var __component__ = /*#__PURE__*/__normalizer(
_sfc_main,
_sfc_render,
Expand Down Expand Up @@ -137,7 +137,7 @@ var __component__ = /*#__PURE__*/__normalizer(

let resolvedMap: RawSourceMap | undefined = scriptMap

output.push(`export default __component__.exports`)
output.push(`export default /*#__PURE__*/ __getExports(__component__)`)

// handle TS transpilation
let resolvedCode = output.join('\n')
Expand Down
9 changes: 8 additions & 1 deletion src/utils/componentNormalizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@ export const NORMALIZER_ID = '\0plugin-vue2:normalizer'
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
export const normalizerCode = `
export default function normalizeComponent (
// Used to facilitate tree-shaking since property access is not guaranteed to be pure
export function getExports (
component
) {
return component.exports
}
export function normalizeComponent (
scriptExports,
render,
staticRenderFns,
Expand Down

0 comments on commit 2f53050

Please sign in to comment.