我想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/