standard-things / esm

Tomorrow's ECMAScript modules today!
Other
5.26k stars 146 forks source link

Issues integrating esm hook with mocha #873

Open just-boris opened 4 years ago

just-boris commented 4 years ago

Hello! I am trying to enable ESM with mocha in my setup file:

setup.js

require('esm');

And then I am running mocha as mocha --require setup.js test/**/*.test.js. This fails with SyntaxError: Cannot use import statement outside a module error.

If I am supplying ESM module explicitly via command-line flag, mocha --require esm, this works.

Why is there a difference depending on how I load the module?

For the context, this is my real-world use-case:

require('esm'); // why can't I place ESM here, similar to how I do this with other hooks?
require('ignore-styles');
require('ts-node').register({
   project: `${__dirname}/tsconfig.json`,
});
just-boris commented 4 years ago

P.S. apparently, there is no technical limitation. ESM simply looks for occurrence of esm string in the process arguments. I managed to fool esm by providing a no-op value: mocha --require setup.js --exclude esm. With this flag require('esm') works.

Is there a chance to make it more straightforward to implement?

ivanbacher commented 4 years ago

Hey, I use a mocha config file for this. e.g.

{
  "diff": true,
  "extension": [
    "js"
  ],
  "package": "./package.json",
  "reporter": "nyan",
  "slow": 75,
  "timeout": 5000,
  "ui": "bdd",
  "recursive": true,
  "exit": true,
  "env" : "dotenv_config_path=./env/test-config.env",
  "require": "esm, dotenv/config"
}

and have this is my package.json as a run script

"test": "mocha", 
"test-dev": "mocha --watch --reporter spec",