The Vue3+TypeScript project reported an error: The name "require" could not be found. Do I need to install type definitions for node?

An error is reported when writing code for a Vue3+ TypeScript project: The name "require" cannot be found. Need to install type definitions for node? Try using  npm i --save-dev @types/node

 Description : When developing a project today (the project framework is Vue3+TypeScript ), it is necessary to  dynamically import static resources , that is, the value of the src attribute of the img tag is dynamically obtained. According to the previous practice, it can be directly imported by require, as shown in the following code:

<img class="demo" :src="require(`../../../assets/image/${item.img}`)" />

After writing the code, the wavy line reports an error, and the error message: the name "require" cannot be found. Need to install type definitions for node? Try npm i --save-dev @types/node. ts(2580)
followed the prompts to install @type/node in the command line tool. After installing @type/node, the wavy line still exists, and the problem was not solved. After investigation, it was found that the type type needs to be added to the ts configuration file tsconfig.json. The solution is as
follows Step 1 : Follow the prompts  to install@type/node , and enter the installation command in the prompt in the command line tool

npm i --save-dev @types/node

Step 2 : Open  the project root directory , find  the TypeScript configuration filetsconfig.json , and add the specified type in tsconfig.json type:['node'] , the code is as follows:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "baseUrl": ".",
    "types": [
      "vite/client",
      "node"
     ],
    "lib": [
      "esnext",
      "dom"
    ],
    "paths": {
      "/@/*": [
        "src/*"
      ],
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "src/vendors/coordtransform.js"
    ]
}

After adding require, no error will be reported~

Friendly reminder: If your project uses Vite, that is, the framework is Vue3+TypeScript+Vite, then require cannot be used. There is no static resource loading method like require in vite, so if you want to dynamically load static resources , you should go to vite's official website to find out how vite introduces static resources
or read another blogger's solution to the problem... The address of the blog post is as follows: How Vue3+TypeScript+Vite uses require to dynamically import static resources like pictures

Guess you like

Origin blog.csdn.net/weixin_41012767/article/details/127507839