parceljs - 无法在 TypeScript 中使用 Parcel 导入 ".html" 文件
我正在尝试使用 Typescript 和 Parcel 设置一个简单的项目。
在这个项目中,我正在尝试从一个 .ts 文件导入一个 .html 文件(或者更准确地说,是它的路径):
import html from "../renderer/index.html";
console.log(html); // file:///home/foo/bar/dist/main/renderer.1c7e1d82.html
如在多个地方提到的,为了使其工作,我添加了以下声明文件 html.d.ts:
declare module '*.html' {
const value: string;
export default value
}
以及我的完整 tsconfig.json:
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": false,
"strict": true,
"esModuleInterop": true,
},
"files": [
"src/main/main.ts"
],
"include": ["@types"]
}
配置看起来是正确的,因为我的 IDE 似乎能够识别上面的导入,并且运行 tsc 不会失败,并产生预期的结果 (require("../renderer/index.html"))。
然而,当尝试使用 Parcel 打包(parcel build main.ts)时,虽然编译本身按预期工作,导入被替换为 new URL("renderer.1c7e1d82.html", "file:" + __filename).toString();,但它无法识别 d.ts 文件,并抛出以下警告:
@parcel/transformer-typescript-types: Cannot find module '../renderer/index.html' or its corresponding type declarations.
/home/angrykoala/Desktop/scratchpad/gaucho2/src/main/main.ts:9:18
8 |
> 9 | import html from "../renderer/index.html";
> | ^^^^^^^^^^^^^^^^^^^^^^^^^ Cannot find module '../renderer/index.html' or its corresponding type declarations.
10 | console.log(html)
11 |
根据文档,我的 .pretierrc 设置为使用 tsc:
{
"extends": "@parcel/config-default",
"transformers": {
"*.{ts,tsx}": ["@parcel/transformer-typescript-tsc"]
}
}
然而,它未能考虑 tsconfig 中的 files 或 include 参数。我尝试的任何其他变体(例如删除 files)也都有同样的问题。
答案#1
Parcel 字符串内联是使用 bundle-text: 前缀完成的。
import html from "bundle-text:../renderer/index.html";
Parcel 会自动添加开发依赖 @parcel/transformer-inline-string。
更多信息请访问 https://parceljs.org/features/bundle-inlining。
我通常会创建一个定义文件 global.d.ts,其中包括:
declare module "bundle-text:*" {
const value: string;
export default value;
}
并在 tsconfig.json 中添加这一行 includes: ["**/*.ts"]。
编辑:
关于 tsconfig 的 includes 的更多信息请参见 https://www.typescriptlang.org/tsconfig#include。
请注意,同时包含定义文件也很重要,这由模式 "**/*.ts" 覆盖。
