Commit Graph

149 Commits

Author SHA1 Message Date
mofeiZ
0c28a09eef
[ci] Reduce non-deterministic builds for eslint-plugin-react-hooks (#33026)
See https://github.com/rollup/plugins/issues/1425

Currently, `@babel/helper-string-parser/lib/index.js` is either emitted
as a wrapped esmodule or inline depending on the ordering of async
functions in `rollup/commonjs`. Specifically,
`@babel/types/lib/definitions/core.js` is cyclic (i.e. transitively
depends upon itself), but sometimes
`@babel/helper-string-parser/lib/index.js` is emitted before this is
realized.


A relatively straightforward patch is to wrap all modules (see
https://github.com/rollup/plugins/issues/1425#issuecomment-1465626736).
This only regresses `eslint-plugin-react-hooks` bundle size by ~1.8% and
is safer (see
https://github.com/rollup/plugins/blob/master/packages/commonjs/README.md#strictrequires)

> The default value of true will wrap all CommonJS files in functions
which are executed when they are required for the first time, preserving
NodeJS semantics. This is the safest setting and should be used if the
generated code does not work correctly with "auto". Note that
strictRequires: true can have a small impact on the size and performance
of generated code, but less so if the code is minified.

(note that we're on an earlier version of `@rollup/commonjs` which does
not default to `strictRequires: true`)
2025-04-25 14:26:59 -04:00
lauren
db7dfe0550
[eprh] Don't transpile to es5 (#32669)
Now that we've moved the sync location of the plugin, we no longer need
this since those restrictions no longer apply.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/32669).
* __->__ #32669
* #32668
2025-03-19 11:49:42 -04:00
michael faith
5ccfcd17ff
feat(eslint-plugin-react-hooks): merge rule from eslint-plugin-react-compiler into react-hooks plugin (#32416)
This change merges the `react-compiler` rule from
`eslint-plugin-react-compiler` into the `eslint-plugin-react-hooks`
plugin. In order to do the move in a way that keeps commit history with
the moved files, but also no remove them from their origin until a
future cleanup change can be done, I did the `git mv` first, and then
recreated the files that were moved in their original places, as a
separate commit. Unfortunately GH shows the moved files as new instead
of the ones that are truly new. But in the IDE and `git blame`, commit
history is intact with the moved files.

Since this change adds new dependencies, and one of those dependencies
has a higher `engines` declaration for `node` than what the plugin
currently has, this is technically a breaking change and will have to go
out as part of a major release.

### Related Changes
- https://github.com/facebook/react/pull/32458

---------

Co-authored-by: Lauren Tan <poteto@users.noreply.github.com>
2025-03-12 21:43:06 -04:00
lauren
a8ab2bcb62
[rollup] Add support for running prebuild commands (#32592)
Extracting portions of #32416 for easier review.

Adds a new `prebuild` option to allow for a prebuild command to be run
prior to building the bundle.

Co-authored-by: michael faith <michaelfaith@users.noreply.github.com>
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/32592).
* __->__ #32592
* #32591
* #32590
* #32589
* #32588

---------

Co-authored-by: michael faith <michaelfaith@users.noreply.github.com>
2025-03-12 19:12:45 -04:00
lauren
8646349aeb
[rollup] Fix codeFrame is not a function (#32591)
Extracting portions of #32416 for easier review.

Fixes a small issue where `codeFrame` is not a function when a rollup
error was encountered.

Co-authored-by: michael faith <michaelfaith@users.noreply.github.com>
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/32591).
* #32592
* __->__ #32591
* #32590
* #32589
* #32588

---------

Co-authored-by: michael faith <michaelfaith@users.noreply.github.com>
2025-03-12 19:12:33 -04:00
Ricky
2567726503
[flags] remove enableRemoveConsolePatches (#32425)
wait to merge until we sync
https://github.com/facebook/react/pull/32376, since that enables it in
some testing builds that might break
2025-02-24 10:00:22 -05:00
michael faith
0d9834caeb
build: add support to the rollup build for building typescript packages (#32393) 2025-02-16 10:38:13 -05:00
Sebastian "Sebbie" Silbermann
ed8b68dd17
Stop exporting dev-only methods in OSS production builds (#32200) 2025-02-13 18:26:36 +01:00
Hendrik Liebau
47069f0e80
Build all bundles required by flight fixture with build-for-flight-dev (#30534) 2024-07-31 15:02:36 +02:00
Lauren Tan
70885cfebe
[ci] Cleanup forked build files
Unforks these scripts now that we are fully migrated to GH.

ghstack-source-id: e1e15452f2d2e178a5b56203ebd0b42151e6a9ba
Pull Request resolved: https://github.com/facebook/react/pull/30506
2024-07-29 19:18:02 -04:00
Jack Pope
e4b4aac2a0
Fix existing usage of names/type in build command (#30450)
https://github.com/facebook/react/pull/30422 broke existing build
shortcuts.

Revert the usage of `names` (`_`) and `type` args.

`yarn build-for-devtools` / `yarn build-for-devtools-dev` / `yarn
build-for-devtools-prod` should all work again.

Moved the bundleType documentation into description so they can be fuzzy
matched. But a build like `yarn build --type FB_WWW_PROD` still works
when matched exactly.

There's probably a better way to document the positional `names` arg in
the `--help` command, but didn't see it when browsing the yargs docs so
let's just fix the existing builds for now.

Now:

```
% yarn build --help
yarn run v1.22.19
$ node ./scripts/rollup/build-all-release-channels.js --help
Options:
  --help                Show help                                                                                                                                             [boolean]
  --version             Show version number                                                                                                                                   [boolean]
  --releaseChannel, -r  Build the given release channel.                                                                                   [string] [choices: "experimental", "stable"]
  --index, -i           Worker id.                                                                                                                                             [number]
  --total, -t           Total number of workers.                                                                                                                               [number]
  --ci                  Run tests in CI                                                                                                                 [choices: "circleci", "github"]
  --type                Build the given bundle type. (NODE_ES2015,ESM_DEV,ESM_PROD,NODE_DEV,NODE_PROD,NODE_PROFILING,BUN_DEV,BUN_PROD,FB_WWW_DEV,FB_WWW_PROD,FB_WWW_PROFILING,RN_OSS_DE
                        V,RN_OSS_PROD,RN_OSS_PROFILING,RN_FB_DEV,RN_FB_PROD,RN_FB_PROFILING,BROWSER_SCRIPT)                                                                    [string]
  --pretty              Force pretty output.                                                                                                                                  [boolean]
  --sync-fbsource       Include to sync build to fbsource.                                                                                                                     [string]
  --sync-www            Include to sync build to www.                                                                                                                          [string]
  --unsafe-partial      Do not clean ./build first.     
```
2024-07-25 07:44:57 -04:00
Jack Pope
f6cce072cf
Update yarn build options (#30422)
Improve command documentation and make it easier to build specific
bundle types

**Before**
```
% yarn build --help              
yarn run v1.22.19
$ node ./scripts/rollup/build-all-release-channels.js --help
Options:
  --help                Show help                                                                                   [boolean]
  --version             Show version number                                                                         [boolean]
  --releaseChannel, -r  Build the given release channel.                         [string] [choices: "experimental", "stable"]
  --index, -i           Worker id.                                                                                   [number]
  --total, -t           Total number of workers.                                                                     [number]
  --ci                  Run tests in CI                                                       [choices: "circleci", "github"]
  Done in 0.69s.
```

**After**
```
% yarn build --help
yarn run v1.22.19
$ node ./scripts/rollup/build-all-release-channels.js --help
Options:
  --help                Show help                                                                                                               [boolean]
  --version             Show version number                                                                                                     [boolean]
  --releaseChannel, -r  Build the given release channel.                                                     [string] [choices: "experimental", "stable"]
  --index, -i           Worker id.                                                                                                               [number]
  --total, -t           Total number of workers.                                                                                                 [number]
  --bundle              Build the given bundle type.
           [choices: "NODE_ES2015", "ESM_DEV", "ESM_PROD", "NODE_DEV", "NODE_PROD", "NODE_PROFILING", "BUN_DEV", "BUN_PROD", "FB_WWW_DEV", "FB_WWW_PROD",
                     "FB_WWW_PROFILING", "RN_OSS_DEV", "RN_OSS_PROD", "RN_OSS_PROFILING", "RN_FB_DEV", "RN_FB_PROD", "RN_FB_PROFILING", "BROWSER_SCRIPT"]
  --ci                  Run tests in CI                                                                                   [choices: "circleci", "github"]
  --names               Build for matched bundle names. Example: "react-test,index.js".                                                           [array]
  --pretty              Force pretty output.                                                                                                    [boolean]
  --sync-fbsource       Include to sync build to fbsource.                                                                                       [string]
  --sync-www            Include to sync build to www.                                                                                            [string]
  --unsafe-partial      Do not clean ./build first.                                                                                             [boolean]
  Done in 0.61s.
```

Changes
- Use yargs to document existing options: `pretty`, `sync-fbsource`,
`sync-www`, `unsafe-partial`.
- Move `_` arg to `names` option for consistency with other options and
discoverability through yargs help
- Add `bundle` option in place of `argv.type` that allows choices of any
BundleType to be passed in directly.
2024-07-23 11:27:51 -04:00
Jan Kassens
b7e7f1a3fa
[BE] upgrade prettier to 3.3.3 (#30420)
Mostly just changes in ternary formatting.
2024-07-22 16:09:01 -04:00
Sebastian Markbåge
ff89ba7346
Disable consoleWithStackDev Transform except in RN/WWW (#30313)
Stacked on #30308.

This is now a noop module so we can stop applying the transform of
console.error using the Babel plugin in the mainline builds. I'm keeping
the transform for RN/WWW for now although it might be nice if the
transform moved into those systems as it gets synced instead of keeping
it upstream.

In jest tests we're already not running the forks for RN/WWW so we don't
need it at all there.
2024-07-12 14:39:38 -04:00
nakjun
395e2fc6a0
[chore] Fix TypeError in shouldSkipBundle During yarn build-for-devtools-dev and yarn build-for-devtools-prod Commands (#29906)
## Summary

Fix bundle type filtering logic to correctly handle array input in
argv.type and use some with includes for accurate filtering. This
addresses a TypeError encountered during yarn build-for-devtools-prod
and yarn build-for-devtools-dev commands.

## Motivation

The current implementation of the `shouldSkipBundle` function in
`scripts/rollup/build.js` has two issues:

1. **Incorrect array handling in
`parseRequestedNames`([#29613](https://github.com/facebook/react/issues/29613)):**
    
The function incorrectly wraps the `argv.type` value in an additional
array when it's already an array. This leads to a `TypeError:
names[i].split is not a function` when `parseRequestedNames` attempts to
split the nested array, as seen in this error message:
    
    ```
C:\Users\Administrator\Documents\새 폴더\react\scripts\rollup\build.js:76
        let splitNames = names[i].split(',');
                            ^
    TypeError: names[i].split is not a function
    ```
This PR fixes this by correctly handling both string and array inputs in
`argv.type`:
    
    ```diff
    - const requestedBundleTypes = argv.type
    -   ? parseRequestedNames([argv.type], 'uppercase')
+ const argvType = Array.isArray(argv.type) ? argv.type : [argv.type];
    + const requestedBundleTypes = argv.type
    +   ? parseRequestedNames(argvType, 'uppercase')
    ```
    
2. **Inaccurate filtering logic in
`shouldSkipBundle`([#29614](https://github.com/facebook/react/issues/29614)):**
    
The function uses `Array.prototype.every` with `indexOf` to check if
**all** requested bundle types are missing in the current bundle type.
However, when multiple bundle types are requested (e.g., `['NODE',
'NODE_DEV']`), the function should skip a bundle only if **none** of the
requested types are present. The current implementation incorrectly
allows bundles that match any of the requested types.
    
    To illustrate, consider the following example output:
    
    ```
    requestedBundleTypes [ 'NODE', 'NODE_DEV' ]
    bundleType NODE_DEV
    isAskingForDifferentType false

    requestedBundleTypes [ 'NODE', 'NODE_DEV' ]
    bundleType NODE_PROD
    isAskingForDifferentType false  // Incorrect behavior
    ```
    
In this case, even though the bundle type is `NODE_PROD` and doesn't
include `NODE_DEV`, the bundle is not skipped due to the incorrect
logic.
    
This PR fixes this by replacing `every` with `some` and using `includes`
for a more accurate check:
    
    ```diff
    - const isAskingForDifferentType = requestedBundleTypes.every(
    -   requestedType => bundleType.indexOf(requestedType) === -1
    - );
    + const isAskingForDifferentType = requestedBundleTypes.some(
    +   requestedType => !bundleType.includes(requestedType)
    + );
    ```
    
This ensures that the bundle is skipped only if **none** of the
requested types are found in the `bundleType`.

This PR addresses both of these issues to ensure correct bundle type
filtering in various build scenarios.


## How did you test this change?

1. **Verification of `requestedBundleTypes` usage in
`shouldSkipBundle`:**

   * I manually tested the following scenarios:
* `yarn build`: Verified that `requestedBundleTypes` remains an empty
array, as expected.
* `yarn build-for-devtools`: Confirmed that `requestedBundleTypes` is
correctly set to `['NODE']`, as in the original implementation.
* `yarn build-for-devtools-dev`: This previously failed due to the
error. After the fix, I confirmed that `requestedBundleTypes` is now
correctly passed as `['NODE', 'NODE_DEV']`.

2. **Debugging of filtering logic in `shouldSkipBundle`:**

* I added the following logging statements to the `shouldSkipBundle`
function to observe its behavior during the build process:

     ```javascript
     console.log('requestedBundleTypes', requestedBundleTypes);
     console.log('bundleType', bundleType);
     console.log('isAskingForDifferentType', isAskingForDifferentType);
     ```

* By analyzing the log output, I confirmed that the filtering logic now
correctly identifies when a bundle should be skipped based on the
requested types. This allowed me to verify that the fix enables building
specific target bundles as intended.
2024-06-20 21:12:41 +01:00
Sebastian Markbåge
6b4646cbd0
Export captureOwnerStacks() only in DEV "react" builds (#29923)
Only with the enableOwnerStacks flag (which is not on in www).

This is a new DEV-only API to be able to implement what we do for
console.error in user space.

This API does not actually include the current stack that you'd get from
`new Error().stack`. That you'd have to add yourself.

This adds the ability to have conditional development exports because we
plan on eventually having separate ESM builds that use the "development"
or "production" export conditions.

NOTE: This removes the export of `act` from `react` in prod (as opposed
to a function that throws) - inline with what we do with other
conditional exports.
2024-06-19 14:19:48 -04:00
Sebastian Markbåge
c2ae9e28bc
Minify DEV bundles with closure (#29809)
The goal is to improve speed of the development by inlining and DCE
unused branches.

We have the ability to preserve some variable names and pretty print in
the production version so might as well do the same with DEV.
2024-06-08 11:15:57 -04:00
Andrew Clark
857ee8cdf9
Don't minify symbols in production builds (#28881)
This disables symbol renaming in production builds. The original
variable and function names are preserved. All other forms of
compression applied by Closure (dead code elimination, inlining, etc)
are unchanged — the final program is identical to what we were producing
before, just in a more readable form.

The motivation is to make it easier to debug React issues that only
occur in production — the same reason we decided to start shipping
sourcemaps in #28827 and #28827.

However, because most apps run their own minification step on their npm
dependencies, it's not necessary for us to minify the symbols before
publishing — it'll be handled the app, if desired.

This is the same strategy Meta has used to ship React for years. The
React build itself has unminified symbols, but they get minified as part
of Meta's regular build pipeline.

Even if an app does not minify their npm dependencies, gzip covers most
of the cost of symbol renaming anyway.

This saves us from having to ship sourcemaps, which means even apps that
don't have sourcemaps configured will be able to debug the React build
as easily as they would any other npm dependency.
2024-04-20 11:23:46 -04:00
Andrew Clark
0e0b69321a
Run Closure on non-minified prod builds, too (#28827)
In #26446 we started publishing non-minified versions of our production
build artifacts, along with source maps, for easier debugging of React
when running in production mode.

The way it's currently set up is that these builds are generated
*before* Closure compiler has run. Which means it's missing many of the
optimizations that are in the final build, like dead code elimination.

This PR changes the build process to run Closure on the non-minified
production builds, too, by moving the sourcemap generation to later in
the pipeline.

The non-minified builds will still preserve the original symbol names,
and we'll use Prettier to add back whitespace. This is the exact same
approach we've been using for years to generate production builds for
Meta.

The idea is that the only difference between the minified and non-
minified builds is whitespace and symbol mangling. The semantic
structure of the program should be identical.

To implement this, I disabled symbol mangling when running Closure
compiler. Then, in a later step, the symbols are mangled by Terser. This
is when the source maps are generated.
2024-04-19 14:22:38 -04:00
Josh Story
da6ba53b10
[UMD] Remove umd builds (#28735)
In React 19 React will finally stop publishing UMD builds. This is
motivated primarily by the lack of use of UMD format and the added
complexity of maintaining build infra for these releases. Additionally
with ESM becoming more prevalent in browsers and services like esm.sh
which can host React as an ESM module there are other options for doing
script tag based react loading.

This PR removes all the UMD build configs and forks.

There are some fixtures that still have references to UMD builds however
many of them already do not work (for instance they are using legacy
features like ReactDOM.render) and rather than block the removal on
these fixtures being brought up to date we'll just move forward and fix
or removes fixtures as necessary in the future.
2024-04-17 11:15:27 -07:00
Sebastian Markbåge
dc3178151b
Add ignoreList to our source maps (#28310)
All our sources are considered third party and should be hidden in stack
traces unless expanded. Our internals aren't actionable anyway.

This doesn't really do much without tooling that actually forwards this
to new generated source maps, in which case they probably just add them
to ignorelist anyway.
2024-02-13 12:54:06 -05:00
Ruslan Lesiutin
78c71bc545
refactor[ci/build]: dont generate sourcemaps for BROWSER_SCRIPT bundles (#27665)
Instead of https://github.com/facebook/react/pull/27664, we can just
exclude `unstable_server-external-runtime.js` from having sourcemaps for
now.

We should consider removing manual copying of this artifact in
52d542ad6d/.github/workflows/commit_artifacts.yml (L136-L138)


As described in https://github.com/facebook/react/pull/27664, this
artifact doesn't have any effect on the `hash`, which is used for
generating React version identifier.
2023-11-09 16:11:17 +00:00
Ruslan Lesiutin
c47c306a7a
refactor[ci/build]: preserve header format in artifacts (#27671)
In order to make Haste work with React's artifacts, It is important to
keep headers in this format:
```
/**
* ...
...
* ...
*/
```

For optimization purposes, Closure compiler will actually modify these
headers by removing * prefixes, which is expected.
We should pass sources to the compiler without license headers, with
these changes the current flow will be:
1. Apply top-level definitions. For UMD-bundles, for example, or
DEV-only bundles (e. g. `if (__DEV__) { ...`)
2. Apply licence headers for artifacts with sourcemaps: oss-production
and oss-profiling bundles, they don't need to preserve the header format
to comply with Haste. We need to apply these headers before passing
sources to Closure, so it can build correct mappings for sourcemaps.
3. Pass these sources to closure compiler for minification and
sourcemaps building.
4. Apply licence headers for artifacts without sourcemaps: dev bundles,
fb bundles. This way the header style will be preserved and not changed
by Closure.
2023-11-09 16:00:21 +00:00
Mark Erikson
2c8a139a59
Generate sourcemaps for production build artifacts (#26446)
<!--
  Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.

Before submitting a pull request, please make sure the following is
done:

1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
  2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
  9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
  10. If you haven't already, complete the CLA.

Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->

## Summary

This PR updates the Rollup build pipeline to generate sourcemaps for
production build artifacts like `react-dom.production.min.js`.
 
It requires the Rollup v3 changes that were just merged in #26442 .

Sourcemaps are currently _only_ generated for build artifacts that are
_truly_ "production" - no sourcemaps will be generated for development,
profiling, UMD, or `shouldStayReadable` artifacts.

The generated sourcemaps contain the bundled source contents right
before that chunk was minified by Closure, and _not_ the original source
files like `react-reconciler/src/*`. This better reflects the actual
code that is running as part of the bundle, with all the feature flags
and transformations that were applied to the source files to generate
that bundle. The sourcemaps _do_ still show comments and original
function names, thus improving debuggability for production usage.

Fixes #20186 .




<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

This allows React users to actually debug a readable version of the
React bundle in production scenarios. It also allows other tools like
[Replay](https://replay.io) to do a better job inspecting the React
source when stepping through.

## How did you test this change?

- Generated numerous sourcemaps with various combinations of the React
bundle selections
- Viewed those sourcemaps in
https://evanw.github.io/source-map-visualization/ and confirmed via the
visualization that the generated mappings appear to be correct

I've attached a set of production files + their sourcemaps here:


[react-sourcemap-examples.zip](https://github.com/facebook/react/files/11023466/react-sourcemap-examples.zip)

You can drag JS+sourcemap file pairs into
https://evanw.github.io/source-map-visualization/ for viewing.

Examples:

- `react.production.min.js`:


![image](https://user-images.githubusercontent.com/1128784/226478247-e5cbdee0-83fd-4a19-bcf1-09961d3c7da4.png)

- `react-dom.production.min.js`:


![image](https://user-images.githubusercontent.com/1128784/226478433-b5ccbf0f-8f68-42fe-9db9-9ecb97770d46.png)

- `use-sync-external-store/with-selector.production.min.js`:


![image](https://user-images.githubusercontent.com/1128784/226478565-bc74699d-db14-4c39-9e2d-b775f8755561.png)


<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2023-11-07 18:59:27 +00:00
Josh Story
5623f2acf9
Updating forking implementation to match against more general fork implementations (#27205)
Search for more generic fork files if an exact match does not exist. If
`forks/MyFile.dom.js` exists but `forks/MyFile.dom-node.js` does not
then use it when trying to resolve forks for the `"dom-node"` renderer
in flow, tests, and build

consolidate certain fork files that were identical and make semantic
sense to be generalized
add `dom-browser-esm` bundle and use it for
`react-server-dom-esm/client.browser` build
2023-08-17 15:17:46 -07:00
dan
175962c10c
Fix remaining CommonJS imports after Rollup upgrade (#26473)
Follow-up to https://github.com/facebook/react/pull/26442.

It looks like we missed a few cases where we default import a CommonJS
module, which leads to Rollup adding `.default` access, e.g.
`require('webpack/lib/Template').default` in the output.

To fix, add the remaining cases to the list of exceptions. Verified by
going through all `externals` in the bundle list, and manually checking
the webpack plugin.
2023-03-25 00:05:23 +00:00
Mark Erikson
909c6dacfd
Update Rollup to 3.x (#26442)
<!--
  Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.

Before submitting a pull request, please make sure the following is
done:

1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
  2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
  9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
  10. If you haven't already, complete the CLA.

Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->

## Summary

This PR:

- Updates Rollup from 2.x to latest 3.x, and updates associated plugins
- Updates deprecated / altered config settings in the Rollup plugin
pipeline
- Fixes some file extension and import issues related to use of ESM in
`react-dom-webpack-server`
- Removes a now-obsolete `strip-unused-imports` Rollup plugin
- <s>Fixes an _existing_ bug with the Rollup 2.x plugin pipeline on
`main` that was causing parts of `DOMProperty.js` to get left out of the
`react-dom-webpack-server` JS bundles, by adding a new plugin to tell
Rollup to treat that file as if it as side effects</s>

This PR should be functionally identical to the other existing "Rollup 3
upgrade" PR at #26078 . I'm filing this as a near-duplicate because I'm
ready to push this change through ASAP so that I can follow it up with a
PR that adds sourcemap support, that PR's artifact diffing seems like
it's possibly stuck and I want to compare the build results, and I've
got this set up against latest `main`.

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

This gets React's build setup updated to the latest Rollup version,
which is generally a good practice, but also ensures that any further
Rollup config tweaks can be done using the current Rollup docs as a
reference.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->

- Made builds from the latest `main`
- Updated Rollup package versions and cross-compared the changes I
needed to make locally to get successful builds vs #26078
- Diffed the output folders between `main` and this PR, and confirmed
that the bundle contents are identical (with the exception of version
strings and the `react-dom-webpack-server` bundle fix re-adding missing
`DOMProperty.js` content)
2023-03-24 18:08:41 +00:00
Sebastian Markbåge
60144a04da
Split out Edge and Node implementations of the Flight Client (#26187)
This splits out the Edge and Node implementations of Flight Client into
their own implementations. The Node implementation now takes a Node
Stream as input.

I removed the bundler config from the Browser variant because you're
never supposed to use that in the browser since it's only for SSR.
Similarly, it's required on the server. This also enables generating a
SSR manifest from the Webpack plugin. This is necessary for SSR so that
you can reverse look up what a client module is called on the server.

I also removed the option to pass a callServer from the server. We might
want to add it back in the future but basically, we don't recommend
calling Server Functions from render for initial render because if that
happened client-side it would be a client-side waterfall. If it's never
called in initial render, then it also shouldn't ever happen during SSR.
This might be considered too restrictive.

~This also compiles the unbundled packages as ESM. This isn't strictly
necessary because we only need access to dynamic import to load the
modules but we don't have any other build options that leave
`import(...)` intact, and seems appropriate that this would also be an
ESM module.~ Went with `import(...)` in CJS instead.
2023-02-21 13:18:24 -05:00
Sebastian Silbermann
c7967b194b
Distribute bundles more evenly into CI shards (#26208)
## Summary

Previously, we distributed bundles into shards and then checked if we
need to actually build that bundle. This can under-utilize shards
heavily (e.g.
https://app.circleci.com/pipelines/github/facebook/react/38611/workflows/df9e56e7-d476-49ee-9392-d8b37c81aa66/jobs/630545/parallel-runs/28?filterBy=ALL
only building a single bundle).

This won't result in an optimal distribution but, if we're lucky, we
might end up with shard #26 not taking 7mins anymore. The slowest shard
ultimately decicdes when we can start with testing builds.

## How did you test this change?

- [x] `CIRCLE_NODE_INDEX=28 CIRCLE_NODE_TOTAL=40 yarn build` building
more than 1 bundle
- [x] Check timings of `yarn_build` so that we don't up with an
over-stuffed shard (e.g. a shard having to build all the expensive
bundles). Casually dropping 60min idle time 🎉:
- Before:
https://app.circleci.com/pipelines/github/facebook/react/38683/workflows/a41533d7-811c-439d-9751-214ba06035c5/jobs/632230/timing
- After:
https://app.circleci.com/pipelines/github/facebook/react/38686/workflows/8a770df6-5b3e-41ea-b3b5-10abeae703e7/jobs/632247/timing
2023-02-20 22:16:23 +01:00
Sebastian Markbåge
80cf4a099e
Update Closure Compiler (#26205)
I need it for https://github.com/facebook/react/pull/26187.

We need to specify specifically the output mode `ECMASCRIPT5_STRICT` to
remove `const` from the Fizz runtime.
2023-02-20 13:27:13 -05:00
Glenn 'devalias' Grant
6b6d0617ef
Update Rollup and related plugins to their most recent versions (#24916)
Update Rollup and related plugins to their most recent versions +
resolve any breaking changes/deprecations/etc along the way. I made each
change piece by piece, so the commit history tells a pretty good story
of what was changed where/how/why.

fixes https://github.com/facebook/react/issues/24894

For the full deepdive/context, see:

- https://github.com/facebook/react/issues/24894

The inspiration for this came from @jasonwilliams 's PR for attempting
to add sourcemap output support to React's builds:

- https://github.com/facebook/react/issues/20186
  - https://github.com/facebook/react/pull/21946

But I figured that it would be useful to minimise the scope of changes
in that PR, and to modernise the build tooling along the way.

If any of these updates rely on a node version later than `10.x`, then
the following PR may have to land first, otherwise things might break on
AppVeyor:

- https://github.com/facebook/react/issues/24891
  - https://github.com/facebook/react/pull/24892

Co-authored-by: Sebastian Markbage <sebastian@calyptus.eu>
2023-02-20 01:35:56 -05:00
Ming Ye
bc38a3dfa7
Update rollup config to use moduleSideEffects (#26199)
## Summary

In rollup v1.19.4, The "treeshake.pureExternalModules" option is
deprecated. The "treeshake.moduleSideEffects" option should be used
instead, see
https://github.com/rollup/rollup/blob/v1.19.4/src/Graph.ts#L130.

## How did you test this change?

ci green
2023-02-20 00:04:26 -05:00
Sebastian Markbåge
ef9f6e77b8
Enable passing Server References from Server to Client (#26124)
This is the first of a series of PRs, that let you pass functions, by
reference, to the client and back. E.g. through Server Context. It's
like client references but they're opaque on the client and resolved on
the server.

To do this, for security, you must opt-in to exposing these functions to
the client using the `"use server"` directive. The `"use client"`
directive lets you enter the client from the server. The `"use server"`
directive lets you enter the server from the client.

This works by tagging those functions as Server References. We could
potentially expand this to other non-serializable or stateful objects
too like classes.

This only implements server->server CJS imports and server->server ESM
imports. We really should add a loader to the webpack plug-in for
client->server imports too. I'll leave closures as an exercise for
integrators.

You can't "call" a client reference on the server, however, you can
"call" a server reference on the client. This invokes a callback on the
Flight client options called `callServer`. This lets a router implement
calling back to the server. Effectively creating an RPC. This is using
JSON for serializing those arguments but more utils coming from
client->server serialization.
2023-02-09 19:45:05 -05:00
Jan Kassens
6b30832666
Upgrade prettier (#26081)
The old version of prettier we were using didn't support the Flow syntax
to access properties in a type using `SomeType['prop']`. This updates
`prettier` and `rollup-plugin-prettier` to the latest versions.

I added the prettier config `arrowParens: "avoid"` to reduce the diff
size as the default has changed in Prettier 2.0. The largest amount of
changes comes from function expressions now having a space. This doesn't
have an option to preserve the old behavior, so we have to update this.
2023-01-31 08:25:05 -05:00
Ming Ye
bbf4d22113
Update import for babel-code-frame in build script (#25963)
## Summary

Updating import for babel-code-frame to use the official @babel package,
as babel-code-frame is a ghost dependency. This change is necessary to
avoid potential issues and stay up-to-date with the latest version of
@babel/code-frame, which is already declared in our project's
package.json.

## How did you test this change?
yarn test
2023-01-05 15:56:31 -05:00
Jan Kassens
b83baf63f7
Transform updates to support Flow this annotation syntax (#25918)
Flow introduced a new syntax to annotated the context type of a
function, this tries to update the rest and add 1 example usage.

- 2b1fb91a55 already added the changes
required for eslint.
- Jest transform is updated to use the recommended `hermes-parser` which
can parse current and Flow syntax and will be updated in the future.
- Rollup uses a new plugin to strip the flow types. This isn't ideal as
the npm module is deprecated in favor of using `hermes-parser`, but I
couldn't figure out how to integrate that with Rollup.
2023-01-05 15:41:49 -05:00
Jan Kassens
420f0b7fa1
Remove Reconciler fork (1/2) (#25774)
We've heard from multiple contributors that the Reconciler forking
mechanism was confusing and/or annoying to deal with. Since it's
currently unused and there's no immediate plans to start using it again,
this removes the forking.

Fully removing the fork is split into 2 steps to preserve file history:

**This PR**
- remove `enableNewReconciler` feature flag.
- remove `unstable_isNewReconciler` export
- remove eslint rules for cross fork imports
- remove `*.new.js` files and update imports
- merge non-suffixed files into `*.old` files where both exist
(sometimes types were defined there)

**#25775**
- rename `*.old` files
2022-12-01 23:06:25 -05:00
Colin McDonnell
56ffca8b9e
Add Bun streaming server renderer (#25597)
Add support for Bun server renderer
2022-11-17 13:15:56 -08:00
Andrew Clark
54f0e0f730
Scaffolding for react-dom/unstable_external-server-runtime (#25482)
* Scaffolding for react-dom/unstable_external-server-runtime

Implements a new bundle type for in our build config called
BROWSER_SCRIPT. This is intended for scripts that get delivered straight
to the browser without needing to be processed by a bundler. (And also
doesn't include any extra UMD crap.)

Right now there's only a single use case so I didn't stress about making
it general purpose.

The use case is: a script that loads the Fizz browser runtime, and sets
up a MutationObserver to receive instructions as HTML streams in. This
will be an alternative option to the default Fizz behavior of sending
the runtime down as inline script tags, to accommodate environments
where inline script tags are not allowed.

There's no development version of this bundle because it doesn't contain
any warnings or run any user code.

None of the actual implementation is in this PR; it just sets up the
build infra.

Co-authored-by: Mofei Zhang <feifei0@fb.com>

* Set BUNDLE_SCRIPT's GCC output format to ES5

This removes the automatic 'use strict' directive, which we don't need.

Co-authored-by: Mofei Zhang <feifei0@fb.com>
2022-10-14 23:29:17 -04:00
Sebastian Markbåge
80170a0681
Match bundle.name and match upper case entry points (#24346)
Fix matching in the build script.

It's possible to provide a custom bundle name in the case we build deep
imports. We should match those names as a convenience.

The script also calls toLowerCase on requested names but some entries have
upper case now.
2022-04-11 21:01:48 -04:00
Sebastian Markbåge
1ad8d81292
Remove object-assign polyfill (#23351)
* Remove object-assign polyfill

We really rely on a more modern environment where this is typically
polyfilled anyway and we don't officially support IE with more extensive
polyfilling anyway. So all environments should have the native version
by now.

* Use shared/assign instead of Object.assign in code

This is so that we have one cached local instance in the bundle.

Ideally we should have a compile do this for us but we already follow
this pattern with hasOwnProperty, isArray, Object.is etc.

* Transform Object.assign to now use shared/assign

We need this to use the shared instance when Object.spread is used.
2022-02-23 19:34:24 -05:00
Andrew Clark
7034408ff7
Follow-up improvements to error code extraction infra (#22516)
* Output FIXME during build for unminified errors

The invariant Babel transform used to output a FIXME comment if it
could not find a matching error code. This could happen if there were
a configuration mistake that caused an unminified message to
slip through.

Linting the compiled bundles is the most reliable way to do it because
there's not a one-to-one mapping between source modules and bundles. For
example, the same source module may appear in multiple bundles, some
which are minified and others which aren't.

This updates the transform to output the same messages for Error calls.

The source lint rule is still useful for catching mistakes during
development, to prompt you to update the error codes map before pushing
the PR to CI.

* Don't run error transform in development

We used to run the error transform in both production and development,
because in development it was used to convert `invariant` calls into
throw statements.

Now that don't use `invariant` anymore, we only have to run the
transform for production builds.

* Add ! to FIXME comment so Closure doesn't strip it

Don't love this solution because Closure could change this heuristic,
or we could switch to a differnt compiler that doesn't support it. But
it works.

Could add a bundle that contains an unminified error solely for the
purpose of testing it, but that seems like overkill.

* Alternate extract-errors that scrapes artifacts

The build script outputs a special FIXME comment when it fails to minify
an error message. CI will detect these comments and fail the workflow.

The comments also include the expected error message. So I added an
alternate extract-errors that scrapes unminified messages from the
build artifacts and updates `codes.json`.

This is nice because it works on partial builds. And you can also run it
after the fact, instead of needing build all over again.

* Disable error minification in more bundles

Not worth it because the number of errors does not outweight the size
of the formatProdErrorMessage runtime.

* Run extract-errors script in CI

The lint_build job already checks for unminified errors, but the output
isn't super helpful.

Instead I've added a new job that runs the extract-errors script and
fails the build if `codes.json` changes. It also outputs the expected
diff so you can easily see which messages were missing from the map.

* Replace old extract-errors script with new one

Deletes the old extract-errors in favor of extract-errors2
2021-10-31 15:37:32 -07:00
Brian Vaughn
4ba20579da
Scheduling Profiler: De-emphasize React internal frames (#22588)
This commit adds code to all React bundles to explicitly register the beginning and ending of the module. This is done by creating Error objects (which capture the file name, line number, and column number) and passing them explicitly to a DevTools hook (when present).

Next, as the Scheduling Profiler logs metadata to the User Timing API, it prints these module ranges along with other metadata (like Lane values and profiler version number).

Lastly, the Scheduling Profiler UI compares stack frames to these ranges when drawing the flame graph and dims or de-emphasizes frames that fall within an internal module.

The net effect of this is that user code (and 3rd party code) stands out clearly in the flame graph while React internal modules are dimmed.

Internal module ranges are completely optional. Older profiling samples, or ones recorded without the React DevTools extension installed, will simply not dim the internal frames.
2021-10-21 14:40:41 -04:00
Andrew Clark
a724a3b578
[RFC] Codemod invariant -> throw new Error (#22435)
* Hoist error codes import to module scope

When this code was written, the error codes map (`codes.json`) was
created on-the-fly, so we had to lazily require from inside the visitor.

Because `codes.json` is now checked into source, we can import it a
single time in module scope.

* Minify error constructors in production

We use a script to minify our error messages in production. Each message
is assigned an error code, defined in `scripts/error-codes/codes.json`.
Then our build script replaces the messages with a link to our
error decoder page, e.g. https://reactjs.org/docs/error-decoder.html/?invariant=92

This enables us to write helpful error messages without increasing the
bundle size.

Right now, the script only works for `invariant` calls. It does not work
if you throw an Error object. This is an old Facebookism that we don't
really need, other than the fact that our error minification script
relies on it.

So, I've updated the script to minify error constructors, too:

Input:
  Error(`A ${adj} message that contains ${noun}`);
Output:
  Error(formatProdErrorMessage(ERR_CODE, adj, noun));

It only works for constructors that are literally named Error, though we
could add support for other names, too.

As a next step, I will add a lint rule to enforce that errors written
this way must have a corresponding error code.

* Minify "no fallback UI specified" error in prod

This error message wasn't being minified because it doesn't use
invariant. The reason it didn't use invariant is because this particular
error is created without begin thrown — it doesn't need to be thrown
because it's located inside the error handling part of the runtime.

Now that the error minification script supports Error constructors, we
can minify it by assigning it a production error code in
`scripts/error-codes/codes.json`.

To support the use of Error constructors more generally, I will add a
lint rule that enforces each message has a corresponding error code.

* Lint rule to detect unminified errors

Adds a lint rule that detects when an Error constructor is used without
a corresponding production error code.

We already have this for `invariant`, but not for regular errors, i.e.
`throw new Error(msg)`. There's also nothing that enforces the use of
`invariant` besides convention.

There are some packages where we don't care to minify errors. These are
packages that run in environments where bundle size is not a concern,
like react-pg. I added an override in the ESLint config to ignore these.

* Temporarily add invariant codemod script

I'm adding this codemod to the repo temporarily, but I'll revert it
in the same PR. That way we don't have to check it in but it's still
accessible (via the PR) if we need it later.

* [Automated] Codemod invariant -> Error

This commit contains only automated changes:

npx jscodeshift -t scripts/codemod-invariant.js packages --ignore-pattern="node_modules/**/*"
yarn linc --fix
yarn prettier

I will do any manual touch ups in separate commits so they're easier
to review.

* Remove temporary codemod script

This reverts the codemod script and ESLint config I added temporarily
in order to perform the invariant codemod.

* Manual touch ups

A few manual changes I made after the codemod ran.

* Enable error code transform per package

Currently we're not consistent about which packages should have their
errors minified in production and which ones should.

This adds a field to the bundle configuration to control whether to
apply the transform. We should decide what the criteria is going
forward. I think it's probably a good idea to minify any package that
gets sent over the network. So yes to modules that run in the browser,
and no to modules that run on the server and during development only.
2021-09-30 12:01:28 -07:00
Dan Abramov
7b84dbd169
Fail build on deep requires in npm packages (#21063) 2021-03-24 02:43:55 +00:00
Sebastian Markbåge
504222dcd2
Add Node ESM build option (#20243)
This allows exporting ESM modules for the Webpack plugin. This is necessary
for making a resolver plugin. We could probably make the whole plugin
use ESM instead of CJS ES2015.
2020-11-13 05:57:45 -08:00
Dominic Gannaway
b61174fb7b
Remove the deprecated React Flare event system (#19520) 2020-08-05 15:13:29 +01:00
Sebastian Markbåge
ab1f517000
isFBBundle should be true if it's FB for www or FB for RN (#19420)
This ensures that the .fb.js override files kick in for RN. Otherwise we
won't have FB specific exports in the isomorphic modules.
2020-07-20 10:37:04 -07:00
Sebastian Markbåge
76f157e3dd
Add simple Node build (#19022)
The webpack plugin doesn't really need a separate prod and dev build.
It also needs to be ES2015 otherwise we can't extend native classes.
2020-05-28 15:56:34 -07:00
Sebastian Markbåge
60afa3c117
Lint bundles using the bundle config instead of scanning for files (#19025)
* Lint bundles using the bundle config instead of scanning for files

This ensures that we look for all the files that we expect to see there.
If something doesn't get built we wouldn't detect it.

However, this doesn't find files that aren't part of our builds such as
indirection files in the root. This will need to change with ESM anyway
since indirection files doesn't work. Everything should be built anyway.

This ensures that we can use the bundles.js config to determine special
cases instead of relying on file system conventions.

* Run lint with flag
2020-05-28 15:04:25 -07:00