首页 > 解决方案 > 配置 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>

标签: typescriptwebpack

解决方案


您的目录“types/”包含一个具有以下内容的文件:

declare module "html!*" {
    const value: string
    export default value
}

此目录必须可从包含的路径("include"文件中的选项tsconfig.json)访问。

请注意,该"typeRoots"选项不应用于包含您自己的类型。当使用@typesnpm 系统时,可以选择使 TypeScript 编译器机制可配置。


推荐阅读