Home > front end >  How do I import a module with type in nodejs 16?
How do I import a module with type in nodejs 16?

Time:11-01

So, I am using Node16/Typescript and am trying to import discord.js.

I would like to use import syntax, and not the require since I am more used to it, and also cause TS automatically add the types of what I import.

But sadly, it's such a mess, and there is so many import/require syntax that I never know what to do.

So I did this :

import dotenv from 'dotenv';
import { Client, Intents } from 'discord.js';

with the simple tsconfig

        "target": "es2020"
        "module": "es2020" 
        "moduleResolution": "node"

but when I run my code it fail.

TypeError: Cannot read properties of undefined (reading 'minLength') at file:///C:/Users/xxxx/Documents/Repository/xxxx/node_modules/@discordjs/builders/dist/index.mjs:1:831 at ModuleJob.run (node:internal/modules/esm/module_job:185:25) at async Promise.all (index 0) at async ESMLoader.import (node:internal/modules/esm/loader:281:24) at async loadESM (node:internal/process/esm_loader:88:5) at async handleMainPromise (node:internal/modules/run_main:65:12)

I know discord.js is exported as commonJs so I used require instead.

Now the code works, but the type are not found for what I import, and eslint complain of

Require statement not part of import statement.

I tried all the other import / require solution but still nothing works, either it require type : module in package.json but the code won't work, either ts complain about how I import things...

basically if I use the way I want import { Client, Intents } from 'discord.js'; the code don7t work but the compiler and VsCode autocomplete everything and know the type (and eslint have no error)

const Discord = require('discord.js'); will have no types, eslint will complain but the code will work...

what should I do ?

CodePudding user response:

target means that typescript is compiled to that target. Usually we use es2015 for this purpose to maximize supported platforms. What you want is lib.

"target": "es2015",
"lib": ["es2020"]

CodePudding user response:

There is a problem with your tsconfig.json.
It should be:

"target": "es2015"

After changing this, run tsc -p tsconfig.json again.

  • Related