![](/img/trans.png)
[英]SyntaxError: Cannot use import statement outside a module on node.js
[英]Get Cannot use import statement outside a module in node.js
我对 node.js 很陌生,并按照教程使用node v13.6.0
。 我想将is-empty'
导入此文件:
const Validator = require('validator');
import isEmpty from './is-empty';
module.exports = function validateRegisterInput(data) {
let errors = {};
if(Validator.isLength(data.name), {min:2, max: 30}) {
errors.name = 'name is too short or too long';
}
return {
errors,
isValid: isEmpty(errors)
}
}
但我得到这个错误:
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1060:16)
at Module._compile (internal/modules/cjs/loader.js:1108:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)
at Module.load (internal/modules/cjs/loader.js:993:32)
at Function.Module._load (internal/modules/cjs/loader.js:892:14)
at Module.require (internal/modules/cjs/loader.js:1033:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (/home/me/myapp/routes/api/users.js:12:31)
at Module._compile (internal/modules/cjs/loader.js:1144:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)
at Module.load (internal/modules/cjs/loader.js:993:32)
at Function.Module._load (internal/modules/cjs/loader.js:892:14)
at Module.require (internal/modules/cjs/loader.js:1033:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (/home/me/myapp/server.js:7:15)
at Module._compile (internal/modules/cjs/loader.js:1144:30)
is-empty
定义如下:
const isEmpty = value =>
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0);
module.exports = isEmpty
我想知道我该如何解决这个问题?
您应该使用 require 而不是 import 如https://nodejs.org/api/esm.html#esm_package_json_type_field中所述
const Validator = require('validator');
const isEmpty = require('./is-empty');
module.exports = function validateRegisterInput(data) {
let errors = {};
if(Validator.isLength(data.name), {min:2, max: 30}) {
errors.name = 'name is too short or too long';
}
return {
errors,
isValid: isEmpty(errors)
}
}
``
他们想说的是,你不能将两者混为一谈。 你可以使用 ESM 并且只使用require
或者你可以使用import
。 由于 Node 已经将您的 javascript 视为 commonJS 模块,因此您可以使用导入,但是在您引入 require 的那一刻,整个事情就崩溃了。
我刚刚使用了一个使用 requires 的旧 protractor 项目。 要么全无,要么全无。
https://nodejs.org/api/esm.html#esm_interoperability_with_commonjs
不支持使用 require 加载 ES 模块,因为 ES 模块具有异步执行。 相反,使用 import() 从 CommonJS 模块加载 ES 模块。
https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs
没有 require、exports 或 module.exports
大多数情况下,可以使用 ES 模块导入来加载 CommonJS 模块。
如果需要,可以使用 module.createRequire() 在 ES 模块中构建 require function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.