Repository navigation
Description
Current Problems & Scenarios
To have the most performant web app, users have to leverage Rollup to package libs and webpack consume those libs: webpack when it bundles, contains module wrappers and runtimes for running in the browser or another support target (IE: node, electron etc.). People can choose to create a UMD, or CommonJS output, however when this format is consumed by webpack (for another application), this adds un-removable overhead in build sizes. Therefore we have recommended in the past that developers who are using webpack, but also creating component libraries that webpack consumes, that they leverage tooling like RollupJS so that the bundling is as efficient as possible. This not only causes unnecessary work, but more mental cost & time on our users to leverage separate tooling.
Build overhead not just size: On top of that, any time webpack consumes a webpack bundle, it will have to parse and evaluate all code paths that are bundled. If you build a library once, and you are not actively developing it in your application, webpack shouldn't have to build it at all except once
Building component libraries and monorepo's" When your project/application scales, both problem one and two will become more prevalent, as you are building the app and adding needs O(x*buildTime) the time complexity of build out the library itself.
Processing non-js assets: To complicate things, if you tried to build a .vue or .css in js component, you would have to set library-specific loaders and plugins or ship the raw source so that your app build could consume.
Proposed Solution
New reusable caching primitives: We can solve a majority of these problems above via implementation of a new persistent caching primitive. By short circuiting the Compilation#seal() phase, and forcing webpack to output the dependency graph (JSON? Protobuf? Flatbuf?) to disk, we could (in theory) cut half of the build time complexity from webpack.
From there, webpack will collect this webpackGraph (similar to records.json) and hydrate this information into the full object modeled Dependency Graph which is stored in memory during build today. This would happen near the same time that records.json would be processed, however we would need to have the capability to merge the graphs together, before the Compilation#seal() phase (where everything is optimized and put into chunks and chunkGroups, etc).
[Unsure about this] In addition, loaders that are applied to said component library (could?) be referenced and leveraged from original components node_modules so that there is determinism between the loaders used in an application bundle and ones being used to create the library.
User Stories (That speak in solving spirit of these problem areas)
| Priority | Story |
|---|---|
| 1 | As a library author, I can publish a "webpackGraph" file alongside another target that webpack can consume. This graph contains serialized information about modules, dependencies, and their graph relation to eachother (in addition to loaders applied, module and dependency types, and EntryPoint cacheGroups) |
| 1 | As a web application users, I can consume a libraries "webpackGraph" file w/o any configuration (automatically resolved). In addition, when I modify parts of my application, webpack will not traverse, resolve, or parse (?) the original library sources. |
Non-Goals
- We will not focus (in this RFC) creating an "ESM" library target output. This is something we need, but outside of the scope of this spec.
- We will not support legacy module types, shimmed modules, or any Variable Injection due to ProvidePlugin. We primarily want to focus on webpack's first class module types and key loaders.
Requirements
-
Creation of Graph Hydration and DeHydration API's - This enables us to take the circular referencing complex object graph, and store it into a file state (json, protobuf, flatbuf, snapshot?). If serialization is expensive we should explore C, C++, Rust, WASM Compilable friendly alternatives with JS fallback.
-
Compilation will build graph and serialize it if specific options.target, [or whatever named] property is set. Whether or not the graph is serialized piece by piece or all at once should be chose based on a combination of performance and maintainability. After
Compilation#finishModuleswebpack should exit/return as if the build was complete [aka no chunk processing etc]. -
Compilation will collect and load graph in memory at the same
recordsis detected this is also loaded into a in memory module build cache once hydrated. As webpack traces the application graph, it will first check to see if instances of modules already exist with same identifiers and omit the cost of tracing them. -
A lib/component that is using the webpackGraph target, should fail if they are using AMD, CJS, ProvidePlugin(), or anything that will cause fully dynamic nature or extra complexities or dimensions to walking the graph.
-
A webpackGraph lib that is consumed should be on average the same build time as if it was a DLL module.
Questions
-
How would same-loaders with different options from lib to app differentiate their functionality? I believe they will reference the same location with different options so is this an issue?
-
When should the webpackGraph hydrate? (My feeling is when a module that resolves, if it has a graphCache in the same root path as the module being resolved, that webpack would favor the cache and start tracing and hydrating that part of the graph).
Fundementals
0CJS
Is there a zero config story here? What is the cost of discovering webpackGraph's imperatively while modules resolve? What's the perf win from declaring them up front. What does this mean for users.
Speed
This ideally improves speed fundamentals.
Build Size
Does this compromise build sizes at all?
Security
Does this open areas of concern for vulnerabilities?
Success Metric
- webpack build times should significantly decrease for those consuming component libraries
- webpack build times should significantly decrease for those creating webpackGraph library targets
- Reduction in memory footprint(?).
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
[-][Spec: webpack 5] - `target.webpackGraph` - Persistent graph target[/-][+][spec: webpack 5] - `target.webpackGraph` - Persistent graph target[/+]mzgoddard commentedon Jan 26, 2018
@TheLarkInn This spec is awesome. I've thought of something similar along this line of thought a few times working on
hard-source-webpack-plugin.So relaying on what I've experienced maintaining and further developing hard-source:
How will webpack 6 work with this?
A big question this will need to answer is forward and backwards compatibility. Will webpack 6 be able to use version 5 graphs? Does it choose parts of version 5 graphs to use piecemeal?
How do library authors support webpackGraph releases when webpack 6 first comes out? Do they publish the library containing both webpack 5 and 6 graphs? Does a single graph support containing both? Does webpack 6 create webpack 5 graphs or do library authors have to use webpack-version-manager to produce both?
Externals? A library depends on lodash for example.
With an aim at performance in regards to time used to build and output size a webpackGraph will want to only include the libraries own files. They can rely on package.json to state semver's of dependencies they depend on as libraries already do.
I think this would be a default behaviour for a webpackGraph target.
This affects other details for a webpackGraph. I leave those details to what they affect.
Caching Primitives
I'm going to list a set of primitives that I think will help maturing this spec. Some of these may be using the idea of primitives loosely be larger caching values but I think they'll help.
primitives
I think dehydrating this set of objects will be easy. That's probably because I've been working on this "area" of webpack for so long. 😄 Or rather the direct dehydrating and hydrating of these types is not the hard part. Its the surrounding API that gives the flexibility to make it easy.
The troubling recursive parts are minimal. Dehydrating these types, most of the needed values to hydrate are options to their constructors. A small list of other needed values are set by Helpers in webpack. The list is easy to track down, but better we make those more "visible" in webpack 5 so they are easier to maintain. Visibility will probably be something like jsdocs at minimum.
For the dependencies, most of the needed values to hydrate are the arguments passed to their constructors. (This is one of the parts that will possibly make figuring out forward and backwards compatibility happen as dependencies change between major webpack versions. Either changing their arguments, or removing and adding whole new dependency types.
NormalModule I think may illustrate another part of dehydrating. Relationship of what we dehydrate to lifecycle. A Module goes through three primary stages, in part represented by its methods:
constructor(),build(), andsource(). For NormalModule the interesting times to dehydrate it are after these calls finish or their callbacks are called (constructor()isn't really useful to dehydrate but inside it and the super classes are a lot of the needed values listed for NormalModule).build()is the most useful, dehydrating the modules blocks, dependencies, and original source (the parsed output from the loaders).source()is useful, after it the rendered ReplaceSource can be dehydrated. Maybe like these there are methods we could add to Dependency and Source types to illustrate their lifecycle stages (and internal values) we want to dehydrate. Again though I think jsdocs and updating some constructors to assign null, false, or empty strings to members they may gain but start at that point with.Some values are not needed. A key example is
originModuleinHarmonyImportDependency. Its set to the module that has that dependency object. Hydrating dependencies I think will follow how dependencies are originally created and added to a module through the parser plugins. A shared state object will be used by the hydrating methods soHarmonyImportDependencyfor example can refer to its module. Another harmony value like this isHarmonyExportImportedSpecifierDependency'sotherStarExports.After circular references like that, any others are set by webpack's normal process, and we can probably leave the rest of webpack's existing machinations to do that.
Loaders and Options
The question that may need answering before this one is: How do we tell two different option sets apart? This may mean restricting loader options for webpackGraphs to declarative options. Or if any loader is applied to a graphed module, the stored module will not be used and webpack will build a new module from the original source provided in the library.
webpack may want to add a performance hint if too many modules are rebuilt that are available in graphs.
pitch-loaders like style-loader won't regularly have a real affect on this if they pitch a module with no further loaders, making them depend on a graphed module.
Traverse? Resolve? Parse?
I don't think they'll be parsed.
I do think they'll be traversed and resolved. Both traverse and resolving would allow individual modules to be rebuilt, like if a user wants to super optimize an individual or set of files with a loader. Traversing will also be needed for relying on other dependencies like lodash.
If this is how its done, the graph may be a loose one, containing at a high level internal resolutions and modules. The connections between different modules will be hydrate by webpack's normal behaviour.
Non-JS Assets
CSS might have a clear path. If a user is ok with the css-loader options applied to a graphed CSS module, they could use style-loader or extract-text to load the CSS into the page while style-loader and extract-text will use the graphed module and toString its output CSS as they already do.
Images or other binary assets leave a question. A basic one, url-loader or file-loader? Which should webpackGraph's use? I think the answer may be a new loader (and dependency, parser plugin, and module?) used by graph targets to emit and refer to the asset but leave the
url-orfile-part to downstream users in some fashion.DLL-like performance?
This may be an unfair target but maybe I'm nit picking this a little too much. DLL modules are very lean in the amount of work they have to do. A graphed module in at least production mode will need to render a source and possibly a source map with the expected used imports and exports. A development version might be able to approach a DLL module's build time by including a "prerendered" development source in the graph that disables used exports, thus exporting all exports with their original names.
Disk Format
I'm not sure of all the types of the format but I have some lessons from hard-source for this. However the string version is produced, there should be no giant object stringified at one time, and any stringifying should be done right as that value is written to disk. This is to keep the process from building too large a string (Node on my systems will not make a string bigger than 130MBs and that can happen in large projects if you try to stringify a truly giant object. Leaving stringifying to right before writing an item to disk helps protect against running out of memory. Once the string is written to disk, it's no longer referred to and can be garbage collected. The string can't be garbage collected if you iterate over an array replacing all the objects with their string versions, and then write those strings one at a time to disk. The non stringified version has smaller strings that can be repeatedly referred to, reducing memory needed to represent the dehydrated cache.
With that in mind the dehydrating and hydrating API will probably expect to output an object when dehydrating and input an object when hydrating. Turning the object and turning it into a string or Buffer will be handled by a second step.
On other format details, I'd guess the larger output object might be some kind of tar like or db like format. Either we're likely to read in a whole graph at times, reading one or smaller set of files for performance, or something db like seeking to and reading the needed parts of the graph at that time. Inside would be the individual modules, etc in JSON, protobuf, Flatbuf format along with some table.
I think this comment ended being about how much I was going to answer and too much. ;-)
IgorMinar commentedon Jan 26, 2018
This appears to me as the wrong direction for webpack because of at least the following 3 reasons:
1/ Webpack can't reliably and deterministically recreate library's build environment within an app built environment.
2/ Shipping nonstandard webpack specific build artifacts is going to be a versioning and compatibility headache.
3/ Lastly, the premise of this proposal goes against side-effect free optimizations that for me are the highlight of webpack v4. Just on that basis I find this proposal odd.
Don't go down this path please.
TheLarkInn commentedon Jan 26, 2018
Thank you for this information. And it is exactly the kind of feedback we want.
1 remaining item
IgorMinar commentedon Jan 26, 2018
ESM output (flattened or not) is something that developers will require in the future. So that's the right direction.
Also thinking about how to break up a large monolithic build into several concurrent once is right.
Just don't try to do this for libraries by asking lib owners to ship webpack specific data structures.
mzgoddard commentedon Jan 26, 2018
Same. I think that means this spec would need to deviate one of two ways to answer it. The better way would be not to recreate the library's build environment but verify that the created build environment is the same as the library used. A non-optimal way would be to not need to recreate the build environment.
The "better way" opens a Pandora's box of usability issues for either library authors or users or both. A solution to this solution may be to have the webpack organization own these issues, to produce and keep up to date a mirror of packages built with graphs. I think this would imply a system that does this automatically, building packages possibly using requests for a graph target built with a desired config as hints to reduce down the number of copies built and kept on this system. This is obviously a really big task to fulfill this problem.
The non-optimal way I think relates to how webpack already consumes dependencies. Javascript is the intermediate format that libraries publish for users. Webpack uses javascript as the intermediate formats inbetween loaders, and its the format a module sits in before being transformed into the module's output source with
__webpack_require__, etc. How I was thinking about the graph idea so far was along this line and that primarily the NormalModule'sbuild()method products would be the primary target of things to store. The parts of the webpack build environment that affect that are the loaders applied, the loader context, and parser plugins. Can we verify these parts? How likely are these to be different? If a user's config doesn't modify these for node_modules, can we use the graph then?Standard formats as published intermediate states can be produced by tools and consumed by other tools. I think that would be more likely to be used by developers. Using a standard format if its published with a packge to npm, etc will be healthier for the javascript community.
Using a flattened ESM version (and probably non-flattened ones too) would imply using the config details of whatever build process the published library used to create it. That may reflect some similarity to one of the birds eye goals for this spec. Instead of recreating the build environment any loaders and plugins that would affect consuming a library will be additive instead of replacing them. So do we need to recreate the build environment or just consume as is?
As another standard format we could interact with, it be an ESTree that is produced and consumed.
Yup. Other than producing a (new or old) standard format or having a system to dynamically create these, I also don't see an answer to the versioning and compatibility issues this will have.
I don't think this is correct. I think our primary target for a webpackGraph would dehydrate modules after the
build()stage of their lifecycle. Optimization plugins do not interact with that stage. @IgorMinar can you point to some code I'm overlooking on this part?IgorMinar commentedon Jan 26, 2018
@mzgoddard for production builds of libraries with large number of optional symbols you either want a tool that can do code-splitting at the symbol level (webpack can't do that) or a combo of a tool that can code split on ES module level (webpack v4, but not v3) + libraries that have rich (internal) ES module structure that webpack can traverse and use for code-splitting.
This means that webpack v4 will create better prod bundles if the inputs are not flattened ES Modules, at the cost of processing more files (higher build latency).
We are measuring the impact on Angular ecosystem now, and might end up shipping both flattened ES modules for dev builds (trades off lower build latency for less efficient code splitting) and unflattened ES modules for prod builds (trades off higher build latency for more efficient code splitting).
@filipesilva is exploring this right now.
TheLarkInn commentedon Jan 26, 2018
@IgorMinar does this differ from something like bazel's persistent cache file format? I would even be fine to standardize on a caching format that any tool could pickup also.
Things that surface in my mind that we want to accomplish:
In specific context to angular, I think of people who are putting ngModules in to separate / 100s of packages, but then treat them like separate apps (when really they are like components for your main app). I usually end up seeing people say "how can I get webpack to webpack this, or dynamically load it". How can this story turn into, I build my components with webpack, and then consume that metadata so I don't have to build them again.
IgorMinar commentedon Jan 26, 2018
mzgoddard commentedon Jan 28, 2018
I haven't seen hermetic used this way before. I think I get it but I'm unsure I fully grok it.
webpack modules represent this with their cacheable flag. Modules that are not cacheable are rebuilt for every rebuild after webpack starts in the dev server or with the watch flag. Its rare to have non-cacheable modules in builds. If a module in a build was non-cacheable we'd exclude it from any cache, memory or fs.
I'm doing this for webpack over at https://github.com/mzgoddard/hard-source-webpack-plugin. And futzing through bringing that into webpack's core.
Do you mean how loaders are applied to modules and that may change the graph versus if the loader had not been applied? Wouldn't that be considered an input to the build?
webpack only support statically analyzable dependencies. If a dependency request in a module isn't statically analzyable webpack emits an error on that module.
How I understand these points so far I don't think they'd stop this kind of work. I would like to figure out what intermediate format could be stable for library authors to publish if that is possible.
TheLarkInn commentedon Jan 28, 2018
filipesilva commentedon Jan 29, 2018
I'm a bit late to this thread but there's some things I'd like to discuss.
I don't thinks the way libraries are built should bear any impact to how they are consumed, besides resolution of the appropriate entry point. Build artifacts are, by definition, in the correct format to be consumed. They are already the common agreed interop format. It is a good thing that the individual parts of a build setup produce these intermediate artifacts.
Consuming library assets in an application is not, as far as I know, a solved problem yet. There is agreement in regards to JS and CSS/SCSS/etc module loading, but not for things like images, fonts, etc.
I don't think this proposal (webpackGraph) would help because it would at best solve the problem for webpack users, while leaving other consumers out in the cold. This is already a side effect of how webpack uses loaders and it's not a positive one IMHO. There are already libraries in the wild that need webpack to work.
I don't think there's value in using the same webpack compilation for everything. It's better to split across package boundaries. Publishing build information together with build artifacts assumes the build environment can be replicated.
This is not true in a non-hermetic build system, such as webpack. For starters, webpack uses the node version in the environment. If a package requires a different node version, webpack would have to orchestrate a local hermetic install of that node version, and have a separate compilation inside it. Mind you that this is what Bazel does, and why it's able to guarantee hermeticity.
These assume source code is made available with libraries, and this doesn't seem realistic with third party ones. If we're only talking about local linked development the story might be a bit different. But I don't see why a consuming app needs to know anything about how the consumed library was built.
Or rather, I don't see why consuming your own library needs to be different than consuming a third party library. That it is usually different nowadays is a limitation rather than a feature.
I think this is the right way to think about this problem. 👍
I think it's important to explain what "build" means in the Bazel context. In a webpack context build usually means "build your sources and bundle your vendors". But in Bazel it mostly means just "build your sources".
And it's important to establish this distinction. You can try framing bundling as a build where there's a bunch of sources and that's not wrong. But it is separate from building sources.
Bazel operates as a system level task runner and for that reason it is able to build hermetic environments. This means it can and will build sources with whatever environment they need. It will build some sources with python 2.7 if they need it, and others with python 3.x. Same with node, go, whatever. Whatever compiler and version those sources need. It will completely replicate whatever environment dependencies the source has.
By contrast, webpack cannot orchestrate environment setup. Webpack cannot install node, npm, loaders, or anything else. It uses the available ones. Given the same environment+input+configuration, webpack produces hermetic builds.
This is why
hard-source-webpack-pluginandcache-loaderrequire complex cache key arrangements. They mean to encode environment and configuration requirements in those keys. If either differs from what they expect, they cannot guarantee the same result.An as example, Bazel could orchestrate building several apps where each needed different node environments, different webpack versions, different loader versions, and different plugin versions. Webpack cannot do this.
My opinion on this topic is that it is a worthwhile endeavour for webpack to seek a persistent cache between different builds in the same environment.
The definition of environment here is of the utmost importance. If you assume that the same inputs will yield the same outputs, then you just need to verify the inputs are the same.
Inputs for webpack are generally environment+source files+configuration. The last two are generally under the control of webpack, but environment is not.
For webpack the environment is at least:
There's one environment factor missing from that list that I really hope can not be there: the OS. Because if OS is a relevant part of the environment then there is no hope of doing anything non-local. But local is good as well.
Having established the environment, and verified that it is indeed the same, then it is viable to admit hermeticity within it. In this context it means that the same set of environment+inputs+configuration will yield the same output. Thus it is possible to cache outputs by input.
The inputs for building sources are the sources. The inputs for bundling built sources are the built sources. Configuration is the set of webpack, loader and plugin configuration.
To be perfectly honest
cache-loaderdoes a big part of this already. It caches by source+mtime if I remember correctly.Anything more than this is an optimization, but is not fundamentally different.
The suggested graph format is a cache of an intermediate webpack format. I agree that it could be specified and made common for several tools. But you are simply caching an intermediate computation to avoid doing it again.
The hard part of this problem is not the caching, but rather checking the environment. This is what Bazel truly does very well, because it orchestrates environment creation.
Webpack cannot orchestrate environment creation. But it can verify environments. That is actually enough to create and use a persistent cache.
TheLarkInn commentedon Jan 30, 2018
filipesilva commentedon Jan 30, 2018
I'm sorry but this isn't true.
If you change a loader the build can produce different results for the same input. That's why
hard-source-webpack-pluginhas the environment hash (https://github.com/mzgoddard/hard-source-webpack-plugin#environmenthash).If you change webpack, loader or plugin configuration you can also get different results. Just imagine using
babel-loaderwith a different preset.You need the same environment+sources+configuration to ensure the same results.
You might want to include loaders in your definition of sources but they are not sources, they are pluggable parts of the build system. As far as I know webpack does not verify they haven't changed.
You can say that part of your caching strategy is to throw local cache away when the lockfile changes (that's what
hard-source-webpack-plugindoes) and that's fine. But even though you don't set the environment you still need to verify it. If you don't verify it, you have no way to invalidate the cache.TheLarkInn commentedon Jun 2, 2019
CC'ing @chrisdarroch after our conversions about DLL's
webpack-bot commentedon Jan 15, 2021
This issue had no activity for at least three months.
It's subject to automatic issue closing if there is no activity in the next 15 days.
webpack-bot commentedon Jan 30, 2021
Issue was closed because of inactivity.
If you think this is still a valid issue, please file a new issue with additional information.