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

huangapple go评论63阅读模式
英文:

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?

英文:

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?

答案1

得分: 0

在你的 package.json 文件中添加 "type": "module"。

或者

<script type="module" src="你的脚本地址"></script>

或者使用 require:

const config = require('dotenv');
英文:

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

or

&lt;script type=&quot;module&quot; src=&quot;your script addres&quot;&gt;&lt;/script&gt;

or use require

const config = require(&#39;dotenv&#39;)

huangapple
  • 本文由 发表于 2023年2月8日 16:13:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定