ES6和common js 模块

事情是这样的,想用mocha跑测试,结果一直报各种模块加载错误,比如:

import {expect} from "chai"
^^^^^^

SyntaxError: Cannot use import statement outside a module

看到一篇很好的讲解 es6 commmonjs 模块加载区别的博客Node.js 如何处理 ES6 模块, 做个总结:

Node.js两种模块对比 ES6 module CommonJS module
简称 ESM CJS
使用语言 Node.js专用
加载方式 import (异步) require() (同步)
输出方式 module.exports export
后缀名 .mjs (默认严格模式) .cjs
.js 后缀 "type": "module" "type": "commonjs" package.json 一级字段

其他细节请点击上面链接看原文。

于是在package.json 添加字段 "type": "module" ,继续报错:
Error [ERR_MODULE_NOT_FOUND]: Cannot find module ' 仔细一看是因为 import from 的文件没有加 .js 后缀, 解决方法 Customizing ESM specifier resolution algorithm:
--experimental-specifier-resolution=node
mocha的测试终于跑起来了,完整命令:
npx mocha FILENAME --experimental-specifier-resolution=node

原文地址:https://www.cnblogs.com/mrlonely2018/p/15543767.html