Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Modules and JavaScript Compatibility Mode docs #1489

Merged
merged 21 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7fe9b07
Update Modules and JavaScript Mode docs
ppcano Jan 26, 2024
90ecc4c
Update Javascript Compatibility Mode
ppcano Jan 26, 2024
840ed31
Port changes to v0.49.x
ppcano Feb 7, 2024
235329f
Update docs/sources/next/using-k6/javascript-compatibility-mode.md
ppcano Feb 7, 2024
7fabd09
Update docs/sources/next/using-k6/javascript-compatibility-mode.md
ppcano Feb 7, 2024
2a6e2e9
Update docs/sources/next/using-k6/javascript-compatibility-mode.md
ppcano Feb 7, 2024
43c7cf0
Update docs/sources/next/using-k6/javascript-compatibility-mode.md
ppcano Feb 7, 2024
ba310cb
Update docs/sources/next/using-k6/modules.md
ppcano Feb 7, 2024
877a708
Update docs/sources/next/using-k6/javascript-compatibility-mode.md
ppcano Feb 7, 2024
f50eb3d
Update docs/sources/next/using-k6/javascript-compatibility-mode.md
ppcano Feb 7, 2024
d691a7e
Update docs/sources/next/using-k6/javascript-compatibility-mode.md
ppcano Feb 7, 2024
c5c1edd
Update docs/sources/next/using-k6/modules.md
ppcano Feb 7, 2024
20b2c53
Update docs/sources/next/using-k6/modules.md
ppcano Feb 7, 2024
a19b16d
Update docs/sources/next/using-k6/modules.md
ppcano Feb 7, 2024
ff01755
Update docs/sources/next/using-k6/modules.md
ppcano Feb 7, 2024
3ea11fe
Port Heitor changes to previous versions
ppcano Feb 7, 2024
09e6925
Remove mention about improving startup time
ppcano Feb 14, 2024
8a367ab
Correct the Babel polyfill features
ppcano Feb 14, 2024
95fb2e4
Update `Extension modules` instructions
ppcano Feb 14, 2024
174751f
Update docs/sources/next/using-k6/modules.md
ppcano Feb 14, 2024
3808dea
Fix brower typo
heitortsergent Feb 14, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ weight: 03

Using the [xk6 Docker image](https://hub.docker.com/r/grafana/xk6/) can simplify the process of creating a custom k6 binary. It avoids having to setup a local Go environment, and install xk6 manually.

{{% admonition type="note" %}}

This tutorial is about creating a custom k6 binary (using Docker). If you want to create a Docker image with a custom k6 binary, refer instead to [Using modules with Docker](https://grafana.com/docs/k6/<K6_VERSION>/using-k6/modules/#using-modules-with-docker).

{{% /admonition %}}

## Building your first extension

For example, to build a custom k6 binary with the latest versions of k6 and the [`xk6-kafka`](https://github.com/mostafa/xk6-kafka) and [`xk6-output-influxdb`](https://github.com/grafana/xk6-output-influxdb) extensions, run one of the commands below, depending on your operating system:
Expand Down
198 changes: 54 additions & 144 deletions docs/sources/next/using-k6/javascript-compatibility-mode.md
Original file line number Diff line number Diff line change
@@ -1,44 +1,71 @@
---
title: JavaScript Compatibility Mode
description: 'k6 supports running test scripts with different ECMAScript compatibility modes using --compatibility-mode'
title: JavaScript compatibility mode
menuTitle: JavaScript mode
excerpt: 'k6 supports running test scripts with different ECMAScript compatibility modes using --compatibility-mode'
_build:
list: false
ppcano marked this conversation as resolved.
Show resolved Hide resolved
weight: 19
---

# JavaScript Compatibility Mode
# JavaScript compatibility mode

You can run test scripts with different ECMAScript compatibility modes with the
`run --compatibility-mode` CLI option or `K6_COMPATIBILITY_MODE` environment variable.
You can write k6 scripts in various ECMAScript versions:

Currently two modes are available:
- ES6+ JavaScript with ES modules (ESM).
- ES6+ JavaScript with CommonJS modules.

## Base
k6 supports both module types and most ES6+ features in all k6 execution modes: local, distributed, and cloud.

To enable ES module support, k6 uses [Babel](https://babeljs.io/) internally to transform ESM to CommonJS. The process is as follows:

![Babel transformation in k6](/media/docs/k6-oss/diagram-grafana-k6-babel-pipeline.png)

Some users prefer to bundle their test code outside k6. For this reason, k6 offers two JavaScript compatibility modes:

- [Extended mode](#extended-mode): The default option, supporting ESM and most ES6+ features.
- [Base mode](#base-mode): Limited to CommonJS, excluding the Babel step.

When running tests, you can change the mode by using the `--compatibility-mode` option:

| Env | CLI | Code / Config file | Default |
| ----------------------- | ---------------------- | ------------------ | ------------ |
| `K6_COMPATIBILITY_MODE` | `--compatibility-mode` | N/A | `"extended"` |

## Extended mode

By default, k6 uses the `--compatibility-mode=extended` mode:

{{< code >}}

```bash
$ k6 run script.js
```

{{< /code >}}

As illustrated in the previous diagram, if k6 detects unsupported ES+ features while parsing the test script, it then transforms the script with Babel to polyfill the unsupported features.

Currently, the k6 Babel transformation only adds ESM support and sets `global` (node's global variable) with the value of `globalThis`.

## Base mode

{{< code >}}

```cli
$ k6 run --compatibility-mode=base script.js
```

```bash
```env
$ K6_COMPATIBILITY_MODE=base k6 run script.js
```

{{< /code >}}

Pure Golang JavaScript VM supporting ES5.1+. Use this mode if your scripts are already written
using only ES5.1 features, or were previously transformed by [Babel](https://babeljs.io/),
to reduce startup time, RAM usage and improve performance. See the [k6-es6 project](https://github.com/k6io/k6-es6)
for an example [Webpack](https://webpack.js.org/) setup that does this
transformation outside of k6.
The base mode omits the Babel transformation step, supporting only ES5.1+ code. You may want to enable this mode if your scripts are already written using only ES5.1 features or were previously transformed by Babel.

> ### ⚠️ Disclaimer
>
> Your mileage may vary while running `--compatibility-mode=base` and also importing external dependencies. For instance,
> `xml2js` and `cheerio` currently do not work, while `lodash` does.
Generally, this mode is not recommended as it offers minor benefits in reducing startup time.

### Basic Example
### CommonJS Example

{{< code >}}

Expand Down Expand Up @@ -69,133 +96,16 @@ module.exports.default = function () {
> but it does _not_ support the
> [Node.js module resolution algorithm](https://nodejs.org/api/modules.html#modules_all_together).

### Advanced Example
## Bundling with Babel outside of k6

{{< code >}}

```javascript
const http = require('k6/http');
const metrics = require('k6/metrics');
const k6 = require('k6');
The examples below demonstrate the use of Babel with bundlers like [Webpack](https://webpack.js.org/) and [Rollup](https://rollupjs.org/):

module.exports.options = {
stages: [
{ duration: '30s', target: 20 },
{ duration: '1m30s', target: 10 },
{ duration: '20s', target: 0 },
],
thresholds: {
'failed requests': ['rate<0.1'],
},
};
- [k6-template-es6](https://github.com/grafana/k6-template-es6): Template using Webpack and Babel to bundle k6 tests.
- [k6-rollup-example](https://github.com/grafana/k6-rollup-example): Example using Rollup and Babel to bundle a testing project.

const myFailRate = new metrics.Rate('failed requests');
## Read more

module.exports.default = function () {
const res = http.get('https://httpbin.test.k6.io/');
const checkRes = k6.check(res, {
'status was 200': function (r) {
return r.status == 200;
},
});
if (!checkRes) {
myFailRate.add(1);
}
k6.sleep(1);
};
```

{{< /code >}}

## Extended

{{< code >}}

```bash
$ k6 run --compatibility-mode=extended script.js
```

```bash
$ K6_COMPATIBILITY_MODE=extended k6 run script.js
```

{{< /code >}}

In case of syntax/parsing errors, the script will be transformed using Babel with specific plugins bringing the compatibility to ES2015(ES6)+. This means that features such as classes and arrow functions can be used. This does take some time to transpile and the produced code has slightly different line/column numbers.

Before v0.31.0, k6 included [core.js](https://github.com/zloirock/core-js) v2 and even more Babel plugins in extended mode.
This added around 2MB extra memory usage per VU and some of the transformations (generators, async/await) of Babel were still insufficient to get k6 working with these features.

## Performance Comparison

There's a substantial difference in performance between both modes, as shown by
[GNU time](https://www.gnu.org/software/time/) below, especially when running tests with a large
number of VUs:

{{< code >}}

```bash
$ /usr/bin/time -v k6 run \
--compatibility-mode=base \
--vus 3500 \
--duration=60s \
script.js

[...]
User time (seconds): 15.10
System time (seconds): 10.02
Percent of CPU this job got: 40%
Elapsed (wall clock) time (h:mm:ss or m:ss): 1:01.88
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 903612
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 1
Minor (reclaiming a frame) page faults: 352090
Voluntary context switches: 558479
Involuntary context switches: 4689
Swaps: 0
File system inputs: 0
File system outputs: 78856
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
```

```bash
$ /usr/bin/time -v k6 run \
--compatibility-mode=extended \
--vus 3500 \
--duration=60s \
script.js

[...]
User time (seconds): 104.44
System time (seconds): 6.96
Percent of CPU this job got: 101%
Elapsed (wall clock) time (h:mm:ss or m:ss): 1:49.49
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 7972316
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 1
Minor (reclaiming a frame) page faults: 2595676
Voluntary context switches: 535511
Involuntary context switches: 9306
Swaps: 0
File system inputs: 0
File system outputs: 78856
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
```

{{< /code >}}
- [Native ESM support](https://github.com/grafana/k6/issues/3265): GitHub issue for native ESM support in k6. This feature aims to eliminate the Babel transformation step within k6.
- [Running large tests](https://grafana.com/docs/k6/<K6_VERSION>/testing-guides/running-large-tests): Optimize k6 for better performance.
- [k6 Modules](https://grafana.com/docs/k6/<K6_VERSION>/using-k6/modules): Different options to import modules in k6.
- [k6 Archive Command](https://grafana.com/docs/k6/<K6_VERSION>/misc/archive): The `k6 archive` command bundles all k6 test dependencies into a `tar` file, which can then be used for execution. It may also reduce the execution startup time.
Loading
Loading