【问题标题】:Configuring Typescript to work with html modules配置 Typescript 以使用 html 模块
【发布时间】:2018-11-01 08:26:10
【问题描述】:

我正在尝试使用 typescript 和 webpack 建立一个项目,但是我无法在构建过程中捆绑 html 文件。

我期待index.ts 将所有.html 文件作为字符串导入(它可以很好地导入.ts 文件),这将导致webpack 使用file-loader 捆绑它们并将它们放在dist/examples (因此,如果我有更多 .html 文件,我会将它们导入这里,它们最终也会出现在 dist/examples 中。

我已经尝试过导入的相对名称和绝对名称,但是当我同时使用 webpack 运行以及尝试使用 tsc -p src/tsconfig.json 手动执行时,我得到了错误 TS2307: Cannot find module './file.html'

我对 typescript 相当陌生,这是我第一次使用 .d.ts 文件,但据我了解,index.d.ts 文件应该告诉 typescript 将所有 .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>

【问题讨论】:

  • 在您的tsconfig.json 中,您确定目录types/ 可以从"include" 获得吗?
  • 看起来就是这样,我认为声明typeRoots 将包含该类型目录(因为node_modules/@types 工作得很好),@Paleo 如果您将其复制为答案,我会标记问题已回答,以便您获得积分
  • 好的,完成了..

标签: typescript webpack


【解决方案1】:

您的目录“types/”包含一个文件,其内容如下:

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

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

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

【讨论】:

    猜你喜欢
    • 2022-12-13
    • 1970-01-01
    • 2014-10-02
    • 2020-05-23
    • 1970-01-01
    • 2020-12-08
    • 2019-05-22
    • 2017-05-01
    • 2021-02-18
    相关资源
    最近更新 更多