typescript - 配置 Typescript 以使用 html 模块
问题描述
我正在尝试使用 typescript 和 webpack 设置项目,但是在构建过程中我无法捆绑 html 文件。
我希望index.ts
将所有.html
文件作为字符串导入(它可以.ts
很好地导入文件),这将导致 webpack 使用它们捆绑它们file-loader
并将它们放入dist/examples
(所以如果我有更多.html
文件,我会将它们导入这里并且它们最终会也在dist/examples
)。
我已经为导入尝试了相对名称和绝对名称,但是TS2307: Cannot find module './file.html'
当我同时使用 webpack 运行以及尝试使用tsc -p src/tsconfig.json
.
我对打字稿相当陌生,这是我第一次使用.d.ts
文件,但据我了解,index.d.ts
文件应该告诉打字稿将所有.html
文件解析为字符串。
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: {
main: path.resolve(__dirname, 'src', 'main', 'index.ts'),
html: path.resolve(__dirname, 'src', 'res', 'html', 'index.ts')
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
options: {
configFile: 'src/tsconfig.json',
}
},
{
test: /\.html$/,
loader: 'file-loader',
include: path.resolve(__dirname, 'src', 'res', 'html'),
exclude: /node_modules/,
options: {
name: '[name].[ext]',
outputPath: 'examples',
}
}
]
},
resolve: {
extensions: [ '.ts', '.html', '.js' ]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
};
src/tsconfig.json
{
"compilerOptions": {
"outDir": "../dist/",
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"allowJs": false,
"moduleResolution": "node",
"lib": ["es6", "dom"],
"typeRoots": [ "../node_modules/@types", "../types"],
},
"include": [
"main/**/*",
"res/html/**/*"
],
"exclude": []
}
类型/index.d.ts
declare module '*.html' {
const value: string;
export default value
}
src/res/html/index.ts
import test from './test'
import file from './file.html'
src/res/html/file.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>FILE</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>hello world</h1>
</body>
</html>
解决方案
您的目录“types/”包含一个具有以下内容的文件:
declare module "html!*" {
const value: string
export default value
}
此目录必须可从包含的路径("include"
文件中的选项tsconfig.json
)访问。
请注意,该"typeRoots"
选项不应用于包含您自己的类型。当使用@types
npm 系统时,可以选择使 TypeScript 编译器机制可配置。
推荐阅读
- excel - 通过whatsapp从excel发送图片
- ios - 如何在我的 Flutter 应用中注册 iOS 本机代码中的类?
- flutter - 以墨水飞溅的方式更改按钮的颜色
- python - 基于另一个数据帧计算数据帧中列的值
- python - ModuleNotFoundError:没有名为“cogs”的模块
- shell - 更改两个具有不同日期格式的文件
- git - Git 因致命错误而失败。拒绝将不相关的历史与 git push 合并?
- javascript - 在页脚元素中居中一个 material-ui React 组件
- python - 逻辑回归:X 每个样本有 667 个特征;期待 74869
- r - 大型数据集中的模糊合并