-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Experimental inline / deferred requires optimiser #9221
Merged
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
37e5d9b
Initial implementation of experimental inline requires plugin
marcins fd98780
Refactor visitor class to separate module, add unit tests
marcins 8d11c80
Add basic flowgen types for @swc/core
marcins 263a928
Add flow typing for inline-requires plugin
marcins 0131718
Merge branch 'v2' into mszczepanski/experimental-inline-requires
marcins c127ee3
Remove experimental from pacakge name
marcins e3929bd
Merge branch 'v2' into mszczepanski/experimental-inline-requires
marcins File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
78 changes: 78 additions & 0 deletions
78
packages/optimizers/experimental-inline-requires/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# Inline requires plugin | ||
|
||
This plugin is currently **experimental**, however that said it has been used in a very large web application with great success in reducing runtime startup time of the application. | ||
|
||
## Quick usage | ||
|
||
Add this optimizer to run _first_ (before minification), for JS bundles. | ||
|
||
```json | ||
{ | ||
"optimizers": { | ||
"*.js": { | ||
"parcel-optimizer-experimental-inline-requires", | ||
"..." | ||
} | ||
} | ||
} | ||
``` | ||
|
||
## Background and motivation | ||
|
||
When Parcel produces modules in bundles, where a dependency wasn't brought in by scope hoisting, it includes calls to require those dependencies at the top of the module function. For example, prior to minification, a module might look something like this: | ||
|
||
```js | ||
parcelRegister('abc123', function (require, module, exports) { | ||
var $def456 = require('def456'); | ||
var $ghi789 = require('ghi789'); | ||
|
||
exports.someFunction = function () { | ||
if ($def456.someOperation()) { | ||
return $ghi789.anotherOperation(); | ||
} | ||
return null; | ||
}; | ||
}); | ||
``` | ||
|
||
When the module is first initialised (i.e. the "module factory" is called), this will get the `def456` and `ghi789` modules, immediately calling their module factories, and so on down. However, the two modules don't have any of their code called until the `someFunction` export is called. If, for example, the call site looks like this: | ||
|
||
```js | ||
// other code.. | ||
var $abc123 = require('abc123'); | ||
element.addEventListener('click', () => { | ||
element.innerText = $abc123.someFunction(); | ||
}); | ||
``` | ||
|
||
.. then the code in `abc123` might not be called until much later, or never at all. In a large enough application, the evaluation / execution time of all these factory functions can be noticeable in performance metrics for the application. | ||
|
||
What this plugin does, is it turns those `require` calls into "lazy" or "deferred" evaluation requires - that is, the factory function will only be executed when the module is first used. For the first example, the resulting code (pre-minification) will look like this: | ||
|
||
```js | ||
parcelRegister('abc123', function (require, module, exports) { | ||
var $def456; | ||
var $ghi789; | ||
|
||
exports.someFunction = function () { | ||
if ((0, require('def456')).someOperation()) { | ||
return (0, require('ghi789')).anotherOperation(); | ||
} | ||
return null; | ||
}; | ||
}); | ||
``` | ||
|
||
The minifier will remove the uninitialised variables, and it will also simplify the `(0, ...)` sequence expressions where possible. | ||
|
||
It is important to note, that Parcel will only execute the factory function once. Subseqent calls to `require` will return the module as returned from the original factory. See the `require` code in `packages/packagers/js/src/helpers.js` for how this works. | ||
|
||
## Caveats | ||
|
||
### Overhead | ||
|
||
So the main caveat here is that we're now turning a simple variable access into a function call everytime the module is referenced. For smaller applications, this overhead may not be worth the tradeoff, however for larger applications it might. That's why this plugin is optional, as you need to try it to determine whether or not it works for you. | ||
|
||
### Side-effects | ||
|
||
A module may have side-effects when it is initialised (e.g. setting an event handler on the `window` for example). For assets that Parcel has identified as having side-effects (whether through `package.json` `sideEffects` field, or other heuristics), these modules will _not_ have their `require` calls deferred. |
29 changes: 29 additions & 0 deletions
29
packages/optimizers/experimental-inline-requires/package.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
{ | ||
"name": "@parcel/optimizer-experimental-inline-requires", | ||
"version": "2.9.3", | ||
"license": "MIT", | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"funding": { | ||
"type": "opencollective", | ||
"url": "https://opencollective.com/parcel" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/parcel-bundler/parcel.git" | ||
}, | ||
"main": "lib/InlineRequires.js", | ||
"source": "src/InlineRequires.js", | ||
"engines": { | ||
"node": ">= 14.0.0", | ||
"parcel": "^2.9.3" | ||
}, | ||
"dependencies": { | ||
"@parcel/plugin": "2.9.3", | ||
"@parcel/types": "2.9.3", | ||
"@swc/core": "^1.3.36", | ||
"nullthrows": "^1.1.1" | ||
}, | ||
"devDependencies": {} | ||
} |
65 changes: 65 additions & 0 deletions
65
packages/optimizers/experimental-inline-requires/src/InlineRequires.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
// @flow strict-local | ||
import {Optimizer} from '@parcel/plugin'; | ||
import {parse, print} from '@swc/core'; | ||
import {RequireInliningVisitor} from './RequireInliningVisitor'; | ||
import type {SideEffectsMap} from './types'; | ||
import nullthrows from 'nullthrows'; | ||
|
||
let publicIdToAssetSideEffects = null; | ||
|
||
type BundleConfig = {| | ||
publicIdToAssetSideEffects: Map<string, SideEffectsMap>, | ||
|}; | ||
|
||
// $FlowFixMe not sure how to anotate the export here to make it work... | ||
module.exports = new Optimizer<empty, BundleConfig>({ | ||
loadBundleConfig({bundleGraph, logger}): BundleConfig { | ||
if (publicIdToAssetSideEffects !== null) { | ||
return {publicIdToAssetSideEffects}; | ||
} | ||
|
||
publicIdToAssetSideEffects = new Map<string, SideEffectsMap>(); | ||
logger.verbose({ | ||
message: 'Generating publicIdToAssetSideEffects for require optimisation', | ||
}); | ||
bundleGraph.traverse(node => { | ||
if (node.type === 'asset') { | ||
const publicId = bundleGraph.getAssetPublicId(node.value); | ||
let sideEffectsMap = nullthrows(publicIdToAssetSideEffects); | ||
sideEffectsMap.set(publicId, { | ||
sideEffects: node.value.sideEffects, | ||
filePath: node.value.filePath, | ||
}); | ||
} | ||
}); | ||
logger.verbose({message: 'Generation complete'}); | ||
return {publicIdToAssetSideEffects}; | ||
}, | ||
|
||
async optimize({bundle, options, contents, map, logger, bundleConfig}) { | ||
if (options.mode !== 'production') { | ||
return {contents, map}; | ||
} | ||
|
||
try { | ||
const ast = await parse(contents.toString()); | ||
const visitor = new RequireInliningVisitor({ | ||
bundle, | ||
logger, | ||
publicIdToAssetSideEffects: bundleConfig.publicIdToAssetSideEffects, | ||
}); | ||
visitor.visitProgram(ast); | ||
if (visitor.dirty) { | ||
const newContents = await print(ast, {}); | ||
return {contents: newContents.code, map}; | ||
} | ||
} catch (err) { | ||
logger.error({ | ||
origin: 'parcel-optimizer-experimental-inline-requires', | ||
message: `Unable to optimise requires for ${bundle.name}: ${err.message}`, | ||
stack: err.stack, | ||
}); | ||
} | ||
return {contents, map}; | ||
}, | ||
}); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This file is mostly generated with
flowgen
from the TypeScript types that come with @swc/core.I had to do a little massaging to make them work, but they pass for this repo.