【发布时间】:2020-07-31 09:07:42
【问题描述】:
我正在创建一个脚本,它将在我的系统中运行某些 js 文件(在我的项目之外,实际上它们是 React 应用程序中的纯 js 文件),我想评估它们的内容并获取变量的内容在我的脚本中使用它们。看这里的代码:
import glob from 'glob';
const cwd = '/path/to/code';
const findAll = () => glob('**/*config.js', { cwd }, (err, matches) => {
// matches is an array of paths like ['dir/myfile-config.js']
if (err) {
console.error(err);
return;
}
const file = matches[0];
// file here is the path to a JS file that contains something like export const CONFIG = {prop1: 'value1'};
import(`${cwd}/${file}`)
.then(console.log)
.catch(console.error);
});
当我调用 import() 函数时,它抱怨:
export const CONFIG = {
^^^^^^
SyntaxError: Unexpected token 'export'
但是它正在正确导入“glob”库。我不明白为什么它无法导入该文件,也无法在互联网上找到任何有关它的信息。我可以找到有关如何使节点理解模块系统的信息,但这不是问题,因为我的程序理解导入/导出 sintaxis。 我正在使用节点 12.13.0 运行我的程序,运行文件如下:
node --experimental-modules ./index.js
我也尝试使用节点 13.14.0(删除 --experimental-modules 标志)并得到相同的结果:(
任何帮助将不胜感激。
我还添加了我正在使用的 package.json:
{
"name": "config-retriever",
"version": "1.0.0",
"description": "",
"main": "index.js",
"license": "MIT",
"type": "module",
"private": true,
"dependencies": {
"glob": "^7.1.6"
}
}
【问题讨论】:
-
您好 T.J,感谢您的回复,我已添加包 json。我要导入的文件在这个项目之外,它只是反应应用程序中的一个普通 js 文件,它不在模块或类似的东西中,我的猜测(对内部如何工作的零知识)是问题可能会朝着这个方向发展。
标签: javascript node.js import