Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected token 'export' while importing dynamically a js file

I am creating a script that would run over certain js files in my system (outside my project, actually they are plain js files in a React application) and I want to evaluate the content of them and get the content of the variables to use them in my script. See the code here:

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);
});

When I invoke the import() function it complains about:

export const CONFIG = {
^^^^^^

SyntaxError: Unexpected token 'export'

However it is importing correctly 'glob' library. I don't understand why it cannot import that file and could not find any info in the internet about it. I could find info about how to make node understand the module system but this is not the problem here as my program understands import/export sintaxis. I am running my program with node 12.13.0 running the file like:

node --experimental-modules ./index.js

I also tried with node 13.14.0 (removing the --experimental-modules flag) and got the same result :(

Any help would be really appreciated.

I add also the package.json I am using:

{
  "name": "config-retriever",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "license": "MIT",
  "type": "module",
  "private": true,
  "dependencies": {
    "glob": "^7.1.6"
  }
}

like image 644
A. Llorente Avatar asked Oct 31 '25 14:10

A. Llorente


1 Answers

The problem is that by default, Node.js determines whether something is a CJS module or an ESM module by using its closes package.json. You've said that these configs are outside the project, so there's no package.json to tell Node.js to treat them as ESM rather than CJS.

Options:

  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.

like image 98
T.J. Crowder Avatar answered Nov 02 '25 05:11

T.J. Crowder