json-server运行报错问题

错误一

在vue3项目中创建mock数据的js文件,运行json-server --watch --port 3002 --host 127.0.0.1 data.js报以下错误:

1
2
Error [ERR_REQUIRE_ESM]: require() of ES Module {your path}/homebrew/lib/node_modules/json-server/lib/cli/utils/load.js not supported.
db.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.

翻译为:

1
2
3
db.js被视为ES模块文件,因为它是一个.js文件,其最近的父包.json包含“type”:“module”,它将该包范围内的所有.js文件声明为ES模块。

相反,将db.js重命名为以.cjs结尾,将所需代码更改为使用所有CommonJS模块中可用的动态import(),或将/Volumes/My Hard Drive/code/vue/setup/package.json中的“type”:“module”更改为“type”:“CommonJS”,将所有.js文件视为CommonJS(所有ES模块都使用.mjs)。

解决办法:

package.json文件type属性设置为CommonJS即可解决。

__END__