问题现象
一个简化的例子如下,在我的 index.ts 文件中引入了pug文件
import templateFn from './template/index.pug'
document.body.innerHTML = templateFn({
message: 'Ron!'
})
会发现typescript报错:
找不到模块“./template/index.pug”或其相应的类型声明。 or error TS2307: Cannot find module ‘./template/index.pug’
解决方法
在项目的src目录(或者源码目录)下新建TypeScript声明文件declarations.d.ts :
declare module "*.pug" {
export default function templateFn(locals: object): string
}
如上,我们相当于告诉 ts 我们引入的 .pug文件 是合法的,且默认导出为一个 function。