html - 使用 tsify (Typescript) 时,需要 HTML 文件作为 Browserify 中的模板字符串

标签 html templates typescript browserify

我想require/import HTML 模板作为字符串到我的代码中。但运行时出现一些编译错误。

这是我正在使用的相关 Browserify 设置:

browserify({ basedir: './src' })
    .transform(stringify(['.tpl.html']))
    .add('app.ts')
    .plugin(tsify)

app.ts 中,我想导入一个模板,如下所示:

import template from './app.tpl.html';
console.log(template);

app.tpl.html 可能如下所示:

<h1>Hello!</h1>

我尝试使用 require 而不是 import 进行不同的设置。使用 require 我收到以下错误:

Browserify Error { [TypeScript error: src/components/app.ts(1,9): 
Error TS2304: Cannot find name 'require'.]
message: 'src/components/app.ts(1,9): Error TS2304: Cannot find name \'require\'.',
fileName: 'src/components/app.ts',
line: 1,
column: 9,
name: 'TypeScript error' }

使用 import 找不到模块,出现以下错误:

Browserify Error { [TypeScript error: src/components/test.ts(1,22): Error TS2307: Cannot find module './test.tpl.html'.]
message: 'src/components/test.ts(1,22): Error TS2307: Cannot find module \'./test.tpl.html\'.',
fileName: 'src/components/test.ts',
line: 1,
column: 22,
name: 'TypeScript error' }

我找不到一起使用“stringify”和“tsify”的示例。有没有人有一个将 HTML 模板与“browserify”和“tsify”一起使用的工作示例?

最佳答案

如果你想在 TypeScript 中导入/要求与 TypeScript 模块不同的东西,你需要使用“ native ”require 函数(在本例中由 browserify 定义)。在您告知之前,TypeScript 编译器不会意识到这一点。

declare function require (id: string): any; // declare there will be 'require' function in the runtime 

var template = require('./app.tpl.html'); // use declared function in pure JS

关于html - 使用 tsify (Typescript) 时,需要 HTML 文件作为 Browserify 中的模板字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33033740/

相关文章:

C++ 模板类

c++ - 类型名和标量常量的可变参数模板

typescript - 如何处理 typescript 定义文件中的类型名称冲突

html - 图像下方出现的边界半径

javascript - jQuery 多选项卡脚本不工作

c++ - 如何正确公开基础模板类型以用作类型

node.js - 为什么经典模块解析无法找到我已安装的模块之一?

html - XHTML 和 CSS : Can't seem to fit 3 images in one horizontal list?

html - 图像替换

node.js - 使用 TypeScript 配置 React Native 时出错