diff --git a/docs/recipes/babel.md b/docs/recipes/babel.md index d8875a9bc..fd2d36d1b 100644 --- a/docs/recipes/babel.md +++ b/docs/recipes/babel.md @@ -81,7 +81,7 @@ By default AVA's stage-4 preset will convert ES module syntax to CommonJS. This } ``` -You'll have to use [`@std/esm`](https://github.com/standard-things/esm) so that AVA can still load your test files. +You'll have to use [`@std/esm`](https://github.com/standard-things/esm) so that AVA can still load your test files. [See our recipe for details](./es-modules.md). ## Disable AVA's Babel pipeline diff --git a/docs/recipes/es-modules.md b/docs/recipes/es-modules.md new file mode 100644 index 000000000..720e150ba --- /dev/null +++ b/docs/recipes/es-modules.md @@ -0,0 +1,47 @@ +# Using ES modules in AVA + +As of Node.js 8.5.0, [ES modules](http://2ality.com/2017/09/native-esm-node.html) are natively supported, but behind the `--experimental-modules` command line flag. It works using the `.mjs` file extension. AVA does not currently support the command line option or the new file extension, but you *can* use the [`@std/esm`](https://github.com/standard-things/esm) module to use the new syntax. + +Here's how you get it working with AVA. + +First, install [`@std/esm`](https://github.com/standard-things/esm): + +``` +$ npm install @std/esm +``` + +Configure it in your `package.json` file, and add it to AVA's `"require"` option as well. Make sure to add it as the first item: + +```json +{ + "ava": { + "require": [ + "@std/esm" + ] + }, + "@std/esm": "js" +} +``` + +By default AVA converts ES module syntax to CommonJS. [You can disable this](./babel.md#preserve-es-module-syntax). + +You can now use native ES modules with AVA: + +```js +// sum.mjs +export default function sum(a, b) { + return a + b; +}; +``` + +```js +// test.js +import test from 'ava'; +import sum from './sum.mjs'; + +test('2 + 2 = 4', t => { + t.is(sum(2, 2), 4); +}); +``` + +Note that test files still need to use the `.js` extension. diff --git a/readme.md b/readme.md index b7f6c3e8a..6a604ba88 100644 --- a/readme.md +++ b/readme.md @@ -1140,6 +1140,7 @@ It's the [Andromeda galaxy](https://simple.wikipedia.org/wiki/Andromeda_galaxy). - [TypeScript](docs/recipes/typescript.md) - [Flow](docs/recipes/flow.md) - [Configuring Babel][Babel recipe] +- [Using ES modules](docs/recipes/es-modules.md) - [Testing React components](docs/recipes/react.md) - [Testing Vue.js components](docs/recipes/vue.md) - [JSPM and SystemJS](docs/recipes/jspm-systemjs.md)