Mimic tree-shaking behaviour when importing code from an entry file in development mode.
Note The main execution logic of this plugin only applies to development mode because it
addresses an issue which is specific to development mode.
Install
# Using npm
npm i -D vite vite-plugin-entry-shaking
# Using Yarn
yarn add -D vite vite-plugin-entry-shaking
# Using pnpm
pnpm add -D vite vite-plugin-entry-shaking
Usage
Setup the plugin in your Vite configuration file.
import { resolve } from'path';
import { defineConfig } from'vite';
importEntryShakingPluginfrom'vite-plugin-entry-shaking';
exportdefaultdefineConfig({
plugins: [
EntryShakingPlugin({
targets: [
// Using direct paths.resolve(__dirname, 'src/entry-a')
// Or using glob patterns.
{
glob: 'src/utils/*.ts',
globOptions: { ignore: ['excluded.ts'] },
}
],
}),
],
});
You need to list all of the entry points you want this plugin to process.
extensions
string[]
['js', 'jsx', 'mjs', 'ts', 'tsx', 'mts']
This specifies which file extensions you want this plugin to process.
ignorePatterns
(string | RegExp)[]
[/node_modules/]
This specifies RegExp/string whose matched paths must be ignored by the plugin.
maxWildcardDepth
number
0
How deep should this plugin run static analysis when encountering wildcards?
diagnostics
boolean | DiagnosticsConfig
true
Toggles all diagnostics when set as a boolean, or specific diagnostics when set as an object.
debug
boolean
false
Toggles debug mode. This will print debug logs if Vite's logLevel is set to any other value than 'silent'
Diagnostics configuration
Diagnostics are recommendations/warnings emitted by the plugin as it analyzes the specified entry
files. They aim to help you improve the plugin's efficiency by suggesting changes and provide
explanation on why they were emitted. See
RESOURCES
for a more in-depth insight about possible diagnostics.
Name
Default
Description
definedWithinEntry
true
Emit warning if an entry file defines code that may prevent tree-shaking.
maxDepthReached
true
Emits a warning when max analysis depth was reached when handling wildcard imports.
Examples
Examples illustrating usage and benefits can be found
here. Feel
free to fork and play around. For instance, you can toggle the plugin on and off their respective
vite config file while serving in development mode and see how it affects the amount of requests
made by your browser.
This repository provides a simple CLI to help you quickly scaffold a new example, simply run the
following command from the project's root to get started:
pnpm generate-example
Debugger (experimental)
Version 0.4.0 introduces
a debugger
as an optional dependency. When installed and attached to the plugin, a debugger application will
open alongside your actual application in dev mode. This can help you get an overall idea of what
the plugin is processing and its impacts on performances.
[!NOTE]
This requires installing vite-plugin-entry-shaking-debugger and setting the debug option to true.
Motivation
The problem this plugin tries to address is well described by this
Vite's github issue, so we'll stick to its author's
example. Suppose your codebase contains an index file which is basically used as an entry point to
dispatch code imported from other files. This is a rather common pattern which may be handy and
avoid writing a lot of individual import statements:
// shared/index.tsexport { a } from'./a';
export { b } from'./b';
export { c } from'./c';
Let's pretend you have a module which imports c from that entry point:
// module.tsimport { c } from'./shared';
In development mode, when Vite serves the module.ts file, the browser loads the shared/index.ts
file which initiates requests for all of the three a, b and c modules it relies on. The thing
is, we actually only needed the c module, this results in both a and b requests being
unnecessary!
As your projet and entry points grow, you end up paying the price for the ever-increasing amount of
unnecessary requests and HMR updates, which consumes time and resources. Well, that escalated
quickly. Let's try to work around this…
The idea
The main idea is to rewrite imports from a target entry point and replace them by individual imports
of the actual module. Back with the above example:
// module.tsimport { c } from'./shared';
// gets rewritten as…import { c } from'./shared/c';
This way, the shared/index.ts file is not loaded by the browser anymore and no additional requests
are initiated.
How it works
First of all, the plugin reads all of the target entry files listed in the plugin's targets
option. For each entry file :
It uses es-module-lexer to get a list of
imports and exports.
It stores named exports that are re-exports of code imported from another module and the path they
resolve to. It also stores whether this re-exported code is the default or a named export of its
origin. This lets us correctly rewrite the import using the adequate statement.
It also tracks a mutated version of the entry file where these stored named exports are removed.
This is required because we might still import code which is actually defined within the entry
file, rather than exported from another module. To make these work, we'll still need to serve this
mutated version of the entry file so that this kind of code can be reached.
Whenever Vite serves a file which includes an import which resolved to one of the targets, this
file is transformed to rewrite the relevant import statements. It extracts the list of entities
imported from that entry file, and for each imported entity :
it removes the import statement of that entry file.
if it has a matching stored named export, it adds a direct import to the relevant module's
absolute path, taking into consideration whether it imports a named export or a default export.
If it has no matching stored named export, it is some code which is actually defined within the
entry file. These are batched and eventually add a recomposed import of the target.
When encountering the above latest case, we have the browser still loading the shared/index.ts,
which could therefore trigger unnecessary requests, as described earlier. To prevent this kind of
scenario, any import of an entry point is caught and is forced to serve its mutated version we
stored while parsing the entry point file. This ensures the entry point only imports what it needs
to make the code it explicitly defines work.
Import statements are not cleaned up from analyzed targets. This means if you import code that was
defined within a target, you might still load unnecessary modules. This is by design because
getting rid of unused imports would require us to traverse each target's AST to make sure it is
indeed not used, which would end up quite expensive.
By default, tree-shaking wildcard imports only work when imported path is part of target list.
Other wildcard imports may be handled by setting the maxWildcardDepth option.
Read more
The following syntaxes are not handled:
dynamic imports
import json from './json.json' assert { type: 'json' }
Note This does not mean you should expect errors using these. Instead, it just means the
content they intend to import won't be tree-shaken by the plugin.
Mimic tree-shaking behaviour when importing code from an entry file in development mode.
The npm package vite-plugin-entry-shaking receives a total of 5,082 weekly downloads. As such, vite-plugin-entry-shaking popularity was classified as popular.
We found that vite-plugin-entry-shaking demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.It has 0 open source maintainers collaborating on the project.
Package last updated on 30 Mar 2024
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Malicious Go packages are impersonating popular libraries to install hidden loader malware on Linux and macOS, targeting developers with obfuscated payloads.
Bybit's $1.46B hack by North Korea's Lazarus Group pushes 2025 crypto losses to $1.6B in just two months, already surpassing all of 2024's $1.49B total.
OpenSSF has published OSPS Baseline, an initiative designed to establish a minimum set of security-related best practices for open source software projects.