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 'E:Project\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
翻译之后:ReferenceError:require未在ES模块范围内定义,您可以使用import代替。此文件被视为ES模块,因为它具有“.js”文件扩展名,并且“E:Project\package.json”包含“type”:“module”。要将其视为CommonJS脚本,请重命名为使用“.cjs”文件扩展名。
出现这个错误是因为vue项目的 package.json 文件中,定义了 "type": "module",这表示 Node.js 将默认使用 ES 模块格式来处理 .js 文件。
{
"name": "new-project",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"deploy:dev": "vite build --mode development && set NODE_ENV=dev&& node nodeFile.cjs",
"deploy:test": "vite build --mode test && set NODE_ENV=test&& node nodeFile.cjs",
"deploy:prod": "vite build && set NODE_ENV=prod&& node nodeFile.cjs"
},
....
而我copy之前项目的nodeJS的自动化部署的脚本里面用的是require,而 require 是 CommonJS 模块的语法(懒得改~)。因此使用 require 会导致错误提示。
const compressing = require("compressing"); //这里其实用import就好啦
const { NodeSSH } = require("node-ssh");
const path = require("path");
const fs = require("fs");
const ssh = new NodeSSH();
let NODE_ENV = process.env.NODE_ENV
要解决这个问题,有以下几种方法:
-
使用
import替换require: 如果你希望继续使用 ES 模块,那么需要将require替换为import。对于compressing模块的导入,你可以这样做:import compressing from "compressing";注意,如果你使用的是 ES 模块,确保你使用的所有模块都支持 ES6 的
import语法。 -
将文件扩展名改为
.cjs: 如果你希望继续使用 CommonJS 的require语法,您可以将nodeFile.js文件的扩展名改为.cjs。这样,Node.js 就会将该文件视为 CommonJS 模块,允许使用require。(强烈建议!我是觉得这个贼贼方便!)将文件改名为
nodeFile.cjs,然后可以继续使用require:const compressing = require("compressing"); -
修改
package.json的"type"字段: 如果你希望整个项目使用 CommonJS 模块,你可以将package.json中的"type": "module"删除或改为"type": "commonjs"。但是请注意,这会影响到整个项目中模块的处理方式。(不建议)