Search code examples
javascriptdiscord.js

I am making a Discord bot using Javascript. I am using a .env file and the dotenv library for security. I am getting an error with importing dotenv


I am making my first Discord bot using Javascript. I decided to use a .env file to hide my token so I can push the files to Github. To do that I had to use the dotenv library. When I try to import that library, I get an error.

import { config } from 'dotenv'; ^^^^^^

SyntaxError: Cannot use import statement outside a module

I get this error with the first import statement only, I know that when I switch them I get the same error but with the other one. (I am using nodemon, Discord.js and dotenv only)

import { config } from 'dotenv';
import { Client } from 'discord.js';

config();

const client = new Client({ intents: ['Guilds', 'GuildMessages'] });
const TOKEN = process.env.t;

client.login(TOKEN);

Here is my code.

What did I do wrong? How do I fix this? How do I prevent this in the future? Is there a more efficient way?


Solution

  • Add "type": "module" to your package.json file.

    or

    <script type="module" src="your script addres"></script>
    

    or use require

    const config = require('dotenv')