简体   繁体   中英

Export array to another file in Node.js

I am making a Discord bot using discord.js, and I'm trying to import a huge array called "replies" from a file named "names.js".

names.js

export var replies = ['various stuff'];

bot.js

import {replies} from "names.js";

This just returns me the following error message

(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module '/home/pi/discordbot/monsieur_bot/...'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

I have tried enabling the "type: module" in the packages.json file, but this just breaks my code (the require discord.js bit).

You should use the relative path, since your file is not a node_module.

import { replies } from "./names";

edit: If you cannot use modules on your node aplication, then you need to change your code for something like this:

names.js

exports.replies =  [foo, bar]

bot.js

const { replies } = require("./names.js");

Use Relative Path

names.js

export var replies = ['various stuff'];

bot.js

import { replies } from './names.js';

package.js

  "type": "module"

The paths in node js are relative to the file you are writing an example:

If you are writing in main.js and you want to import a module that is in name.js, assuming it is at the same height in main you would put name from "./name.js".

The keys are put if you are not doing an export default.

Another thing you have to use when you use exports is put in the package-json:

"type": "module",

Blockquote

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM