如何在TypeScript中使用es6语法导入.html片段

rgr*_*per 8 import typescript ecmascript-6

如何从相对路径导入HTML模板,如下所示:

import customSelectHtml from "./custom-select.html!text";
Run Code Online (Sandbox Code Playgroud)

TypeScript编译器抱怨它无法找到模块.我试图创建一个环境模块定义,但它不允许模块名称中的相对路径.我使用SystemJS作为模块加载器.

Mau*_*eys 5

我没有使用打字稿,但确实使用了ES6。可能对您有用。

我解决此问题的方法是使用引号声明模板字符串。它对我来说很好用,如果有人认为这是个坏习惯,我将很高兴知道。

在带有Angular(-ui-router)的代码段下方。

index.js

var indexTemplate = `
<div>
    <h1>{{ Index page }}</h1>
</div
`

export {indexTemplate}
Run Code Online (Sandbox Code Playgroud)

config.js

import { indexTemplate } from './index.js'

function config($stateProvider){
    $stateProvider.state('index', {
        url: '/',
        controller: 'indexController',
        template: indexTemplate
    })
}
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这假设indexController在其他位置定义。另外,此配置功能将导出到定义了应用程序的位置。但这与问题无关。


Ami*_*mid 3

是不可能的。

由于typescript 中模块的定义,以及据我所知 ES6 javascript ( import )。模块不能是 html。常见的方法是导入一个 javascript 模块,该模块导出一个包含 html、css 等的字符串。但这并不是导入原始 html 文件。

也许您还想看看html 导入,但那是完全不同的事情。

  • “typescript 是 javascript 的超集”就这么多&gt;_&lt; (2认同)