Summary:
`metro-bundler` v0.21 contains a rewritten bundling mechanism, with simplified logic and much faster rebuild times, called delta bundler. This release contains a couple of breaking changes:
* Now, when using a custom transformer, the list of additional babel plugins to apply are passed to the `transform()` method. These are used in non-dev mode for optimization purposes (Check 367a5f5db8 (diff-40653f0c822ac59a5af13d5b4ab31d84) to see how to handle them from the transformer).
* Now, when using a custom transformer outputting `rawMappings`, the transformer does not need to call the `compactMappings` method before returning (check d74685fd1d (diff-40653f0c822ac59a5af13d5b4ab31d84) for more info).
* We've removed support for two config parameters: `postProcessModules` and `postProcessBundleSourcemap`.
Reviewed By: davidaurelio
Differential Revision: D6186035
fbshipit-source-id: 242c5c2a954c6b9b6f339d345f888eaa44704579
Summary:
**Summary**
Minification fails or minified bundle may crash due to uglify-es bugs which have been fixed recently. See https://github.com/facebook/react-native/issues/16689
**Test plan**
Try to production bundle a project using ex-navigation, which fails with:
```
Maximum call stack size exceeded
```
Use this patch and see that bundling suceeds. There are also minified runtime errors solved by this change, see https://github.com/facebook/react-native/issues/16689 for more information.
Closes https://github.com/facebook/metro-bundler/pull/85
Reviewed By: mjesun
Differential Revision: D6259177
Pulled By: rafeca
fbshipit-source-id: 55987eb338b06938181c0da74d104d23eeb135b6
Summary:
This diff migrates Metro Bundler from `worker-farm` to `jest-worker`:
* Fully removes the custom patched `worker-farm` fork.
* Removes //a lot// of non-clear Flow types used to cast functions from callbacks to promises.
* Reduces cyclomatic complexity of the `Transformer` class by using `async`/`await`.
* Cleans all additional methods inside `JSTransformer/index.js`, by moving them to a single class and properly scoping them.
**Note:** this diff does not still enable the ability to bind files to workers by using `computeWorkerKey`; this will come at a later stage.
Reviewed By: davidaurelio
Differential Revision: D6247532
fbshipit-source-id: 51259360a5c15117996777a3be74b73b583f595e
Summary: To determine whether segment boundaries are properly covered by async imports rather than requires, we need to get knowledge about it higher up in the stack. This changeset exposes which of the dependencies are async as an array of indices within the `dependencies` array (I'd prefer avoiding duplicating the strings because they could get inconsistent, and I don't want to have 2 separate arrays of names either because we'd have to modify a bunch of stuff across the stack to support that).
Reviewed By: davidaurelio
Differential Revision: D6220236
fbshipit-source-id: 1ee36bc7c59f7f27e089f7771a24c45c8bd57b5d
Summary: Having types in tests ensure that we're testing what the API is supposed to process and not something else. In that case, adding type revealed that we were mistakenly passing strings instead of `Buffer` objects to the transform and optimize functions, but it would still work because `toString` was called over it. Passing proper `Buffer` objects as expected ensures that it doesn't just work with strings, and that the integration of these files in the rest of the application works as expected. This changeset fixes these callsites and add a few invariants here and there. We use `invariant` instead of `expect()` because Flow understands only the former as a type refinement, even though `expect` would also be a form of possible refinement. I don't think it's a big deal.
Reviewed By: davidaurelio
Differential Revision: D6160019
fbshipit-source-id: cbcbb05d7bccf9e1b9f6bb3ea30b0bb2925aef1b
Summary: Here's a good example why Flow "exact types" are useful: there are a few place where we were adding unusused fields in the objects. As these fields end up in JSON files used to communicate with Buck, this can amount to a waste of resources. This changeset make the type exact and removes the unused fields.
Reviewed By: mjesun
Differential Revision: D6159350
fbshipit-source-id: 8cdf29d5729253f119778943ad961eacb8990c04
Summary: This is the last step remaining before enabling the `import()` syntax to use `require.async()` (for now that function is just doing a simple `require()` in behind).
Reviewed By: davidaurelio
Differential Revision: D6147030
fbshipit-source-id: 5cd8ee6cc550816ae3cdea0b457dc2419c99e7a7
Summary:
After checking more deeply, there were still situations where the delta bundler could generate different bundles between runs: when a module is required by two different modules (it has two or more inverse dependencies), that module would not always be inserted after the first inverse dependency in the bundle, which would cause some bundling order discrepancies.
In order to fix that, the bundler now re-traverses synchronously the dependency graph using a DFS traversing algorithm to guarantee the same order. This will add some small runtime overhead (specially when generating the initial bundle), but it's not worrying (from benchmarks in my macbook pro it'll add ~10ms of initial build for every 1000 modules traversed, being this overhead linear).
Reviewed By: mjesun
Differential Revision: D6124993
fbshipit-source-id: 9bc7cb329f01a7860c7d3b52c3376c643ea5cf3b
Summary:
The `formatBanner.js` file is requiring the `wordwrap` package, but it was not defined in the package.json. Somehow this was working before (maybe the package was being downloaded by another depdendency or maybe `formatBanner` was not used).
This fixes https://github.com/facebook/metro-bundler/issues/79
Reviewed By: mjesun
Differential Revision: D6136865
fbshipit-source-id: 722dd61cb936fca893453f4cfc3248718a329779
Summary: This diff fixes https://github.com/facebook/metro-bundler/issues/78 by adding the `runBeforeMainModule` server parameter to the bundler. This is not the cleanest solution, but will be fixed once we use the Delta Bundler for builds from the CLI
Reviewed By: davidaurelio
Differential Revision: D6074469
fbshipit-source-id: 068926ef671d9f897ad9f1bd0540036a97340c00
Summary:
Adds module size as `fb_`-prefixed node attributes to the digraph output of dependencies.
The list of edges is now followed by a list of node declarations, that use the `fb_size` attribute to expose the module size in bytes.
E.g:
```
digraph {
"a" -> "b";
"b" -> "c";
"a"[fb_size=123];
"b"[fb_size=456];
"c"[fb_size=789];
}
```
Reviewed By: fkgozali
Differential Revision: D6064861
fbshipit-source-id: 73127e08c5e38075b5112053de12f9abac1102ee
Summary:
Resolves https://github.com/facebook/metro-bundler/issues/27
**Summary**
There is an edge case where tools like react-primitives need to assign to `Platform.OS`,
but the inline transformation results in an invalid AST.
When Platform.OS is unconditionally inlined, the following scenario:
````
Platform.OS = 'ios';
````
Is transformed to:
```
"ios"="ios"
````
And results in error `Property left of AssignmentExpression expected node to be of a type ["LVal"] but instead got "StringLiteral"**`.
See issue in react-primitives: https://github.com/lelandrichardson/react-primitives/issues/79
This patch checks whether the current node is on the left hand side of an AssignmentExpression
and skips the inlining when this is the case.
It also does the same for `process.env.NODE_ENV`, which suffers from the same problem. See related closed issue https://github.com/facebook/react-native/issues/7607#issuecomment-221425153 which was resolved by using bracket notation `process.env["NODE_ENV"]` instead.
**Test plan**
Unit tests included.
**Notes**
This is my first contribution to Metro, and haven't worked with Babel AST a lot, so constructive feedback on the implementation is welcome.
Closes https://github.com/facebook/metro-bundler/pull/45
Reviewed By: cpojer
Differential Revision: D5974615
Pulled By: mjesun
fbshipit-source-id: 224e63cef24f450b33e17ff9c0e0c0cea46bc70e
Summary:
In order to aid with debugging inline requires we add a method that
will give us the modules.
**Summary**
I was looking for a way to see what modules had been loaded when I was working with inline requires. I had tried using beginEvent on Systrace, but I was worried that there were modules that I might have missed (I'm not certain if all the loaded files are polyfills before the entryFile is invoked for instance). By adding getModules() it simplifies seeing what modules are loaded.
**Test plan**
At the root of my app `index.ios.js`:
```
import App from './App';
import { AppRegistry } from 'react-native';
AppRegistry.registerComponent('App', () => App);
// after 3 seconds the initial app data should have loaded, so lets take a look:
setTimeout(() => {
console.log(require.getModules());
}, 3000);
```
**NOTE**
If there is a way to get to this easily (via the debugger or some other mechanism) I would be happy to use that instead and add documentation for it.
Closes https://github.com/facebook/metro-bundler/pull/37
Differential Revision: D6008180
Pulled By: cpojer
fbshipit-source-id: 850103bbce166bf65a0cbd710582198c66273db5
Summary:
**Summary**
This is the workaround that cpojer suggested in #65 and should resolve the biggest pain point that developers are experiencing in that issue: using moment.js in React Native. Hopefully this at least serves as a starting point to reaching a decent solution for libraries using non-static `require()` statements.
**Test plan**
- Expected error when non-static-argument-based `require()` is nested more than one level deep within a `try` statement
- Expected no error when non-static-argument-based `require()` is nested directly within a `try` statement
```bash
ip-192-168-1-10:trueflipapp richard$ react-native bundle --entry-file index.js --platform ios --bundle-output /tmp/test.js --reset-cache
Scanning folders for symlinks in /repo/trueflip/sandbox/code/trueflipapp/node_modules (8ms)
Scanning folders for symlinks in /repo/trueflip/sandbox/code/trueflipapp/node_modules (8ms)
Loading dependency graph, done.
warning: the transform cache was reset.
bundle: start
bundle: finish
bundle: Writing bundle output to: /tmp/test.js
bundle: Done writing bundle output
```
Closes https://github.com/facebook/metro-bundler/pull/69
Differential Revision: D6008567
Pulled By: cpojer
fbshipit-source-id: f9be328cf50dc47c7433ffeb5eb053b398c92122
Summary:
Hi,
**Summary**
This fixes#40 where bundler cannot resolve a file starting with `.` from the root package directory.
it just adds a check to see if the absolute path filename is the same as the localpath filename then lets it through.
**Test plan**
- Steps to reproduce have been written up in #40
Thanks!
Closes https://github.com/facebook/metro-bundler/pull/54
Reviewed By: cpojer
Differential Revision: D5974618
Pulled By: mjesun
fbshipit-source-id: 4b7113c3bed20f2c908739881d61410d651e6ed7
Summary:
Whitelist node opt `--max-old-space-size` for JSTransformer.
Bundling can choke on the default node memory settings for those of us generating large index.js files. This change allows supplied node options to make it through to the node processes spawned by the JSTransformer worker farm.
Closes https://github.com/facebook/metro-bundler/pull/70
Differential Revision: D6008141
Pulled By: cpojer
fbshipit-source-id: 1ef3b436ea30baf3f255a4fd718fe4d958d70c65
Summary:
Addresses https://github.com/facebook/metro-bundler/issues/62
Apparently with some versions of `jest-haste-map`, the nested source file returns the module wrapped with `default` instead of the exports themselves (due to some ES6 babel transform, I am guessing). I wasn't able to reproduce this myself yet, but I think a good first step is to avoid using nested library files in the first place, ie. only use what's exported at the top-level.
Reviewed By: rafeca
Differential Revision: D5890757
fbshipit-source-id: 1196264b5626eda65c4aae222db2a1620f901c55
Summary: Upgrades uglify to version 3 with (experimental) ES6 support turned on.
Reviewed By: jeanlauliac
Differential Revision: D5842410
fbshipit-source-id: 1c8ccea15785bc5bb1c68d7a83b75881432d0ce2
Summary:
This replaces `async/queue` with a hand-rolled queue that does not yield to the event loop if a unit of work can be run synchronously.
Anecdotally, this leads to a > 11x speedup for the graph traversal when all data is available synchronously, e.g. from an in-memory cache.
Reviewed By: jeanlauliac
Differential Revision: D5861763
fbshipit-source-id: f7cf5f916a13adf9ca418d7522cd2f19df596fba
Summary: Changes `GraphFn` to return a promise rather than taking a callback. This is more in line with call sites, which so far have been using `denodeify`.
Reviewed By: jeanlauliac
Differential Revision: D5857192
fbshipit-source-id: 61bbbef4fbf24b0b91c4a3008541eaa5a1af0f7a
Summary:
Changes `LoadFn` to be synchronous or return a promise, and `ResolveFn` to be synchronsous.
This makes for a nicer API, without losing the property of not yielding to the event loop for synchronous work.
Reviewed By: jeanlauliac
Differential Revision: D5855963
fbshipit-source-id: 4b3c3363f4e49a9890586462925e8e400872feb2
Summary: When running with node 8, the babel plugins `async-to-generator` and `syntax-trailing-function-commas` are unnecessary. Removing them makes runtime transpilation faster, and the resulting code is closer to the original (useful with debugging: less unmapped code areas, better breakpoint support, less renamed variables).
Reviewed By: mjesun
Differential Revision: D5842305
fbshipit-source-id: d99f719794e4a8f48fd10b0349fbb36f2994666e
Summary:
This copies the basic loading mechanism and default config from the RN local cli into Metro and exposes it under `metro-bundler`, and switches internal scripts over to it.
davidaurelio: I changed the packager-worker-for-buck to hardcode the rn.cli file, like we do in other files. I would like to pull the "find" mechanism that traverses up to find a config into Metro at some point, but for now I'd prefer to keep it lean until we need it. Let me know if that doesn't work for you.
The next diff will switch the RN cli over to these functions also.
Reviewed By: davidaurelio
Differential Revision: D5832596
fbshipit-source-id: a3e167644d96c8831e5a83378e8ba143e62426db
Summary: As a first step in defining a new public API and CLI for Metro, I'd like to pull the generally useful pieces from the RN cli into Metro. This diff makes it as a non-breaking change (so we don't have to bump the version of Metro for RN) by updating only the imports outside of the react-native-github folder.
Reviewed By: davidaurelio
Differential Revision: D5832464
fbshipit-source-id: 11b00b5517665441763c2207d577ae0e110c681b
Summary: Fixed the UNBUNDLE magic file location to match what JniJSModulesUnbundle.cpp expects.
Reviewed By: sahrens
Differential Revision: D5821637
fbshipit-source-id: 4342e4bb4d139b4eba77dd92a53b1683041fc7e9
Summary:
This diff renames all the stragglers in comments and strings from variations of "packager" to "Metro Bundler". I did one of three:
* Rename "packager" to "Metro Bundler"
* Rename "react-native-packager" to "Metro Bundler"
* Remove "packager" when code inside of Metro implies that it's about Metro
I also removed `Glossary.md` because it is unmaintained and very old. mjesun is currently starting to write documentation for Metro which will supersede whatever was there before.
Reviewed By: mjesun
Differential Revision: D5802993
fbshipit-source-id: ba99cb5ed04d84b0f7b7a8a0bf28ed99280a940a
Summary: When starting to use `metro-bundler` as a standalone server, I found quite complicated the fact that it needs a transformer by default. Moreover, the transformer is not passed as a reference to a JS object, but as a path to a required file. I removed the need to be required, and defaulted to a dummy, basic transform, that does nothing by default. This avoids having to create an extra file and linking to it (potentially needing to involve `path` and other extra modules).
Reviewed By: cpojer
Differential Revision: D5622906
fbshipit-source-id: 0c2b1bec86fa542b3c05de42c89d4b5bb4384b34
Summary:
<!-- Thanks for submitting a pull request! Please provide enough information so that others can review your pull request. The two fields below are mandatory. -->
**Summary**
<!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? -->
I am sending this PR to fix an error in TransformCaching module. See this issue [TransformCaching module try to collect cache every time I build bundle #46](https://github.com/facebook/metro-bundler/issues/46).
**Test plan**
<!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes UI. -->
```
/**
* When restarting packager we want to avoid running the collection over
* again, so we store the last collection time in a file and we check that
* first.
*/
_collectCacheIfOldSync() {
const {_rootPath} = this;
const cacheCollectionFilePath = path.join(_rootPath, 'last_collected');
const lastCollected = Number.parseInt(
tryReadFileSync(cacheCollectionFilePath) || '',
10,
);
if (
Number.isInteger(lastCollected) &&
Date.now() - lastCollected < GARBAGE_COLLECTION_PERIOD
) {
return;
}
const effectiveCacheDirPath = path.join(_rootPath, CACHE_SUB_DIR);
mkdirp.sync(effectiveCacheDirPath);
collectCacheSync(effectiveCacheDirPath);
fs.writeFileSync(cacheCollectionFilePath, Date.now().toString());
}
```
Steps:
1. Create a new react-native project.
2. Put your breakpoint at this sentence `collectCacheSync(effectiveCacheDirPath);`.
3. Bundle the project, program will break at `collectCacheSync(effectiveCacheDirPath);`
4. Resume the program, finish the first time bundle.
5. Bundle again, this time program won't break.
Closes https://github.com/facebook/metro-bundler/pull/48
Differential Revision: D5726161
Pulled By: jeanlauliac
fbshipit-source-id: 0865f1bf25d6eb36f067ac3dc7764df9fd5026dc
Summary:
The HMR logic used to try to calculate the dependencies of every new added (or modified) file, including assets. This resulted in a TransformError.
This commit adds a check that stops the HMR bundling once it finds out that the updated file is an asset
Reviewed By: cpojer
Differential Revision: D5697391
fbshipit-source-id: faf7ccad76ac4922b70ed1c7ce8ce32b03c4e8ee
Summary: We were not using the timeout at all, so we decided to remove it. Also, the current value is pretty high, so it should never fail unless there's something really bad.
Reviewed By: jeanlauliac
Differential Revision: D5640839
fbshipit-source-id: 3eaa567a6828902376fe5df9fe3f4e96b83a23bd
Summary:
We'll revert when the root problem is fixed, that should mitigate for now.
What might be the root problem, I believe, is that when there are some cached files already on the machine, we immediately try to build all the dependencies, but the worker farm is queuing these and it takes a long time to finish. The timeout should include only the transformation time, not the queuing. I'll fix that separately.
Reviewed By: mjesun
Differential Revision: D5650380
fbshipit-source-id: f4b045876cc822caee3998f69ca98ea986709bf4
Summary: It might be that Metro bundler is getting used directly with the `http` module and not within an express app. If that's the case, the `next` method will not exist, so we have to guard against it.
Reviewed By: davidaurelio
Differential Revision: D5639944
fbshipit-source-id: bcee4a70f6a7b643218b11af0d8aedbc7762eead
Summary: This is the last piece of work to make all the clients do a single request for both HMR/non-HMR modes. I'm not completely sure how this URL is used by the client, but it does not need the `hot` param.
Reviewed By: davidaurelio
Differential Revision: D5639946
fbshipit-source-id: a76f9ba7b9ace625352a156761d3ee2809f80c92
Summary:
This diff enables the HMR transforms for any bundle requested through the metro-bundler HTTP server, so it ignores the `hot` parameter passed in the URL.
This allows much faster switches when enabling/disabling HMR, since metro-bundler does not need to re-compile each single file again, while not impacting substantially build times when HMR is off.
I've done some lightweight benchmarks on my machine and these are the results (all the tests have been done after running metro-bundler with a clean cache and restarting the app).
**Before**
Time to build (HMR off): 1x (baseline)
Time to build (HMR on): 1.90x
**This diff**
Time to build (HMR off): 1.009x
Time to build (HMR on): 1.036x
(The reason why now it takes double the time to load the HMR bundle than the non-HMR bundle after launching the app is because the device after a restart always asks for the non-HMR bundle and afterwards the HMR bundle, causing the server to have to build both bundles).
**Bundle size**
In terms of bundle size, adding the HMR transforms increases the size by around 3-4% (this regression is due to the wrappers added around React components, and will depend on the app).
**Next steps**
There are two improvements to do after this diff:
1. Remove the `hot=true` parameter from the clients when they request the bundle. This will reduce by half the memory used by metro-bundler when switching from non-HMR to HMR (or when opening the app with HMR enabled), since metro-bundler caches the bundles based on url.
2. After this diff, the `hot` parameter in the various options objects will not make much sense, so my suggestion is to just remove it from everywhere and instead of checking for that parameter in the transformer, check for `dev=true` there.
Reviewed By: davidaurelio
Differential Revision: D5623623
fbshipit-source-id: cb76b9182e55f442e2987fcf59eee2ba2571578e
Summary: now that `ResolutionRequest.resolveDependency` is synchronous, we can also make `ResolveFn` synchronous.
Reviewed By: fkgozali
Differential Revision: D5528094
fbshipit-source-id: 0b40df29024b809a99b7e577716b24e9fa499578
Summary: Adds filtering to the assets written from a Buck build, so that we don’t write all assets present in libs, but rather only the ones included in the bundle.
Reviewed By: cpojer
Differential Revision: D5522844
fbshipit-source-id: fcca3567b726dfab1ecf9560932fd6e1a174b31f
Summary: makes flow typing for the entry point more sound and fixes two issues
Reviewed By: BYK
Differential Revision: D5507650
fbshipit-source-id: 6b03f7de792ffcece4d0d61950e136a61ea7db2e