Tree-shaking with ES Modules
Explain how to structure Vue.js 3 applications to leverage ES module imports for tree-shaking, allowing bundlers to exclude unused code.
// utils.js
export function usefulFunction() {
// some useful code
}
export function unusedFunction() {
// some unused code
}
This is a module (utils.js) that exports two functions: one that will be used (usefulFunction) and one that won't be used (unusedFunction).
// main.js
import { usefulFunction } from './utils.js';
usefulFunction();
// Note: We're importing only the usefulFunction and not the unusedFunction. This allows the bundler to only include usefulFunction in the final bundle.
The entry file (main.js) imports only the necessary function from the utils.js module. Since unusedFunction is not imported, it will not be included in the final bundle if the bundler supports tree shaking.
// vue-component.js
<template>
<div>{{ computedProperty }}</div>
</template>
<script>
import { usefulFunction } from './utils';
export default {
name: 'ExampleComponent',
computed: {
computedProperty() {
return usefulFunction();
}
}
};
</script>
This is a Vue.js single-file component that imports only the necessary function (usefulFunction) for use within a computed property. The unusedFunction is not imported, thus not included in the final bundle.