Home>

Tell me how you can organize in node js so that the values ​​of a variable by reference are in a filebig-list.js

export let bigData= [
  'https://google.com',
  'https://habr.com/',
  'https://ru.stackoverflow.com/',
];

was available in another file, sayserver.js

const bigList= require ("big-list.js");
function getResult () {
    return console.log (bigList);
}
getResult ();

What's wrong with the syntax? Why does it give an errorCannot use import statement outside a module?

  • Answer # 1

    In nodejs, the default export goes like this:

    big-list.js

    module.exports= [
      'https://google.com',
      'https://habr.com/',
      'https://ru.stackoverflow.com/',
    ];
    

    server.js

    const bigList= require ("big-list.js");
    console.log (bigList);
    

    But you can add topackage.jsonoption"type": "module"to useimport /export:

    big-list.js

    export default [
      'https://google.com',
      'https://habr.com/',
      'https://ru.stackoverflow.com/',
    ];
    

    server.js

    import bigList from "big-list.js";
    console.log (bigList);
    

    https://learn.javascript.ru/import-export

    https://nodejs.org/docs/latest/api/modules.html

    Thanks, it helped. PS In the second example, only when importing, the path import bigList from "./big-list.js";

    BlackStar19912021-12-16 19:37:32