Home > Software engineering >  importing an exported value from another js file throws unexpected identifier, how do I fix it?
importing an exported value from another js file throws unexpected identifier, how do I fix it?

Time:01-05

There are two js files in my working directory.

Here is the content of test.js

let k; export default k = 12;

Here is the content of test2.js

import m from './test';
console.log(m);

When I tried to run test2.js with node.js (v17.3.0)

node test2.js

I got

import m from './test';
       ^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

The example code comes from MDN doc

Am I using export correctly?

CodePudding user response:

A couple of issues:

  1. You're using ESM syntax, but the CommonJS loader. You need to put "type": "module" in your package.json file to tell Node.js that you're using ESM (or use a .mjs file extension). Details in the documentation.

  2. You've said you're exporting the variable, but you aren't; you're exporting a constant value (12, the result of k = 12) as the default export. To export the variable as the default export, you'd use:

    let k = 12;
    export default k;
    

    The distinction is that if you export the result of k = 12 instead of k, later assignments to k within the exporting module won't update the imported binding's value.


Side note: Default exports are generally not a great idea. Instead, consider using a named export:

// Exporting:
export let k = 12;
// Importing:
import {k as m} from "./test.js";
console.log(m); // 12 (initially, will change if `k` is changed)
  •  Tags:  
  • Related