Setup electron-mocha with @babel/register and TypeScript

Environment

  • Node.js v10.9.0

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"devDependencies": {
"@babel/core": "7.3.3",
"@babel/plugin-proposal-class-properties": "7.3.3",
"@babel/preset-env": "7.3.1",
"@babel/preset-typescript": "7.3.3",
"@babel/register": "7.0.0",
"@types/mocha": "5.2.6",
"electron": "4.0.5",
"electron-mocha": "6.0.4",
"typescript": "3.3.3"
},
"main": "dist/main.js",
"scripts": {
"test": "electron-mocha --require ./babel-register.js src/**/*.test.ts"
},
"version": "0.0.0"
}

babel-register.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
require('@babel/register')({
cache: false,
extensions: ['.ts'],
plugins: ['@babel/proposal-class-properties'],
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'@babel/preset-typescript',
],
});

tsconfig.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"outDir": "dist",
"rootDir": "src",
"target": "es5"
},
"exclude": [
"dist",
"node_modules"
]
}

Takeaways

  • --require ./babel-register.js must be used because you need to specify extensions for TypeScript and this cannot be done when using just --require @babel/register
  • @babel/preset-env is required with a node target because electron-mocha runs in a Node.js environment
  • @babel/preset-typescript is used to turn tests written in TypeScript into JavaScript: https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/
  • The @babel/proposal-class-properties is optional and only required if you code makes already use of class properties

Good to know