Skip to content

Commit

Permalink
add why section
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisbreiding committed Jan 31, 2023
1 parent 1f1f41f commit b98b945
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions docs/api/cypress-api/require.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,32 @@ Cypress.require(
```
<!-- prettier-ignore-end -->

## Why not `require` or `import`?

Cypress runs test code in the browser, so any dependencies have to be bundled
with the test code before it is run. This is accomplished for the majority
of test code via a [preprocessor](/api/plugins/preprocessors-api). However,
due to the way that [`cy.origin()`](/api/commands/origin) works, the callback
passed to it is extracted from the test code where it is defined and run in a
different context. This also separates it from any dependencies that are
included in the test code bundle.

To solve this, we replace all instances of `Cypress.require` with `require` at
runtime and bundle just the callback with any dependencies required within it.

Using `Cypress.require` in the test code instead of `require` or `import` keeps
the dependencies required within the callback from being bundled with the rest
of the test code. We cannot bring them along with the callback to where it is
run, so it would waste execution time and memory to bundle its dependencies in
the original preprocessing. The dependencies are only bundled with the code that
needs them when we preprocess the callback itself.

Additionally, we tried a solution previously that allowed use of `require` and
`import`, but found that it hurt performance not only for spec files using them
within the `cy.origin()` callback, but even for spec files that did not use
them. That solution was also preprocessor-dependent and only worked for the
webpack preprocessor. Using `Cypress.require` is preprocessor-agnostic.

## History

| Version | Changes |
Expand Down

0 comments on commit b98b945

Please sign in to comment.