动态导入JS文件时出现“Unexpected token 'export'”错误

3

我正在创建一个脚本,用于运行我系统中的某些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'库已经正确导入。我不明白为什么无法导入该文件,也没有在互联网上找到任何相关信息。我可以找到关于如何使节点了解模块系统的信息,但这不是问题所在,因为我的程序理解import/export语法。
我正在使用node 12.13.0运行我的程序,例如: node --experimental-modules ./index.js 我还尝试过使用node 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"
  }
}


1
嗨T.J,谢谢回复,我已经添加了package json。我正在尝试导入的文件位于这个项目之外,它只是一个在React应用程序中的普通js文件,不是一个模块或其他什么的,我的猜测(对内部工作原理一无所知)是问题可能出在这个方向上。 - A. Llorente
2个回答

3

问题在于,默认情况下,Node.js 会使用最近的 package.json 来确定某个模块是 CJS 模块还是 ESM 模块。但你说这些配置是在项目外面的,因此没有 package.json 来告诉 Node.js 将它们视为 ESM 而不是 CJS。

解决方案:

  1. Add a package.json to the place where the configs are located that has "type": "module" in it. Literally just this does it:

    {
        "type": "module"
    }
    
  2. You can force that by giving the config files the extension .mjs, which is always treated as an ESM module (and changing your glob call accordingly). For me that's not a great solution, but...

  3. It also may be possible to use the getFormat hook to tell Node that these config files are ESM, not CJS. However, a note on it says that it's in the process of being redesigned and that you shouldn't rely on it.


解决方案1完美地运行了,非常感谢T.J.!解决方案2不是一个选择,因为我想要读取的那些文件是生产代码,我不想搞乱它。我也会考虑解决方案3,并考虑你刚提到的免责声明。目前,我打算在package.json中动态添加"type": "module",并在脚本完成后将其删除,以免污染应用程序的package.json。再次感谢您的超快回复 :) 祝您有个愉快的一天! - A. Llorente
1
@A.Llorente - 啊,我喜欢那个动态的东西!:-) 开心编程! - T.J. Crowder

-1
如果你想在一个js文件中运行特定的函数,你应该使用Make-Runnable模块。
将这段代码片段放在你的js文件的末尾。
require('make-runnable/custom')({
  // printOutputFrame: false
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接