当使用Webpack需要CSS /图像资源时,Typescript编译器"找不到模块"

Cod*_*rer 10 javascript typescript webpack visual-studio-code

我正在编写vanilla Javascript,但使用Typescript编译器的checkJs选项在VSCode中进行类型检查.我有Webpack设置加载各种资产类型(CSS,图像等),这适用于构建,但Code将这些语句视为错误.例如,在此代码中

require("bootstrap");
require("bootstrap/dist/css/bootstrap.css");
var img = require("../img/image.png");
Run Code Online (Sandbox Code Playgroud)

第一行很好,但接下来的两行都在(字符串)参数下显示错误require(),使用工具提示"找不到模块(名称)".

我已经安装@types/webpack@types/webpack-env,其固定resolve()resolve.context().我错过了另一个打字包或者这是我需要在DT问题跟踪器上讨论的问题吗?

Mat*_*ner 15

目前,TypeScript服务器不支持非JS或TS资源,该服务器支持VS Code的JavaScript和TypeScript intellisense.以下是跟踪此问题的问题:https://github.com/Microsoft/TypeScript/issues/15146

要解决此问题,请尝试d.ts使用以下内容在项目中创建文件:

declare module '*.css' { export default '' as string; }
declare module '*.png' { export default '' as string; }
Run Code Online (Sandbox Code Playgroud)

您还可以通过// @ts-ignore在require之前添加来抑制个别错误:

// @ts-ignore
var img = require("../img/image.png");
Run Code Online (Sandbox Code Playgroud)