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

报错信息如下:

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校验里面去掉.

你可能感兴趣的:(javascript,vue.js,前端)