javascript - לא מצליח למצוא את השם 'console'. מה יכול להיות הסיבה לכך?
קטע הקוד הבא מראה שגיאת טייפסקריפט ב-שורה 4:
import {Message} from './class/message';
function sendPayload(payload : Object) : any{
let message = new Message(payload);
console.log(message); // LINE 4
}
השגיאה אומרת:
[ts] Cannot find name 'console'.
מה יכול להיות הסיבה לכך? למה הוא לא יכול למצוא את האובייקט console?
תשובה #1
תצטרך להתקין את @types/node כדי לקבל את טיפוסי ה-node. אתה יכול להשיג זאת על ידי הרצת הפקודה הבאה:
npm install @types/node --save-dev
אם לקובץ tsconfig.json שלך יש את התכונה types, עליך לשנות אותה או שתצטרך לייבא במפורש את סוגי node.js כדי להשתמש בהם:
{
"compilerOptions": {
...
"types": ["jsdom", ...],
...
},
...
תשובה #2
הוסף את "dom" בסעיף lib ב-compilerOptions בקובץ tsconfig.json.
דוגמה:
{
"compilerOptions": {
"rootDir": "src",
"outDir": "bin",
"module": "commonjs",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"target": "es5",
"lib": [
"es6",
"dom" <------- Add this "dom" here
],
"types": [
"reflect-metadata"
],
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
תשובה #3
אתה יכול להריץ npm install @types/node -D, ואז אתה צריך להוסיף גם types:[ 'node'] ל-tsconfig.json שלך.
package.json"devDependencies": {
"@types/node": "^15.0.3"
}
tsconfig.json{
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": ".",
"declaration": true,
"noImplicitAny": true,
"esModuleInterop": true,
"module": "commonjs",
"target": "es6",
"types": [
"node"
],
"lib": [
"es6"
]
},
"exclude": [
"node_modules",
"dist"
]
}
תשובה #4
פשוט הוסף ES6 ו-DOM בקובץ tsconfig.json שלך
"lib": ["ES6", "DOM"]