Setup electron-mocha with @babel/register and TypeScript

Environment

  • Node.js v10.9.0

package.json

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

babel-register.js

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

tsconfig.json

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

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