Permalink
92 lines (71 sloc) 1.72 KB

Using ES modules in AVA

Translations: Français

As of Node.js 8.5.0, ES modules 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 esm module to use the new syntax.

Here's how you get it working with AVA.

First, install esm:

$ npm install esm

Configure it in your package.json or ava.config.js file, and add it to AVA's "require" option as well. Make sure to add it as the first item.

package.json:

{
	"ava": {
		"require": [
			"esm"
		]
	}
}

By default AVA converts ES module syntax to CommonJS. You can disable this.

You can now use native ES modules with AVA:

// sum.mjs
export default function sum(a, b) {
	return a + b;
};
// test.js
import test from 'ava';
import sum from './sum.mjs';

test('2 + 2 = 4', t => {
	t.is(sum(2, 2), 4);
});

You need to configure AVA to recognize .mjs extensions. If you want AVA to apply its Babel presets use the following.

package.json:

{
	"ava": {
		"babel": {
			"extensions": [
				"js",
				"mjs"
			]
		}
	}
}

Alternatively you can use:

{
	"ava": {
		"babel": false,
		"extensions": [
			"js",
			"mjs"
		]
	}
}

Or leave Babel enabled (which means it's applied to .js files), but don't apply it to .mjs files:

{
	"ava": {
		"extensions": [
			"mjs"
		]
	}
}