Typescript编译器“找不到模块”当使用Webpack需要CSS /图像资产时 [英] Typescript compiler "cannot find module" when using Webpack require for CSS/image assets

查看:876
本文介绍了Typescript编译器“找不到模块”当使用Webpack需要CSS /图像资产时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing vanilla Javascript but using the Typescript compiler's checkJs option to do type checking in VSCode. I have Webpack set up to load various asset types (CSS, images, etc), which works fine for builds, but Code is treating these statements as an error. For example, in this code

require("bootstrap");
require("bootstrap/dist/css/bootstrap.css");
var img = require("../img/image.png");

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

the first line is fine but the next two both show an error under the (string) argument to require(), with the tooltip "Cannot find module (name)".

我已安装 @ types / webpack @ types / webpack-env ,修复 resolve() resolve.context()。我错过了另一种打包方式,或者这是我需要处理的问题,我需要了解 DT问题跟踪器

I have installed @types/webpack and @types/webpack-env, which fixed resolve() and resolve.context(). Am I missing another typings package or is this an issue I need to take up on the DT issue tracker?

推荐答案

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

Requiring non JS or TS resources is currently not supported by the TypeScript server which powers VS Code's JavaScript and TypeScript intellisense. Here's the issue tracking this: https://github.com/Microsoft/TypeScript/issues/15146

作为解决方法,请尝试在项目中使用以下内容创建 d.ts 文件:

As a workaround, try creating a d.ts file in your project with the content:

declare module '*.css' { export default '' as string; }
declare module '*.png' { export default '' as string; }

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

You can also suppress individual errors by adding // @ts-ignore before the require:

// @ts-ignore
var img = require("../img/image.png");

这篇关于Typescript编译器“找不到模块”当使用Webpack需要CSS /图像资产时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆