在vue项目里面临时创建js文件想用node执行报错

2023-12-16 12:37:59

报错信息如下:

file:///Users/zhaolan/wangchun/study-json-demo/schema-tests/test1.js:1
const Ajv = require("ajv")
            ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/zhaolan/wangchun/study-json-demo/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///Users/zhaolan/wangchun/study-json-demo/schema-tests/test1.js:1:13
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:34:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

Node.js v20.10.0

解决方案:

其实就是将你要运行的.js文件修改成.cjs就行了,这样es module就不会去校验你的格式了,在这里报错是因为require在eslint里面是不让用的,必须使用import才行,但是我们使用import的话,单纯运行js是导入不进来的,所以只能通过这种方式,或者,你可以选择将当前文件从eslint校验里面去掉.

文章来源:https://blog.csdn.net/weixin_42152604/article/details/135030896
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。