我对webpack还很陌生,现在我第一次在我的angular项目中使用它。
我想在我的html文件中使用require函数来引入一个ng-include的模板,代码如下:
<div ng-include="require(./my-template.html)"></div>
我知道有像 ng-cache 和 ngtemplate 这样的加载器,但它们不符合我的需求。使用它们时,我必须首先在 js 中要求模板,然后在 html 文件中使用模板名称。
如何实现这一点?
我对webpack还很陌生,现在我第一次在我的angular项目中使用它。
我想在我的html文件中使用require函数来引入一个ng-include的模板,代码如下:
<div ng-include="require(./my-template.html)"></div>
我知道有像 ng-cache 和 ngtemplate 这样的加载器,但它们不符合我的需求。使用它们时,我必须首先在 js 中要求模板,然后在 html 文件中使用模板名称。
如何实现这一点?
另一种方法是将 my-template.html
转换成一个Angular组件:
假设您使用html-loader来加载HTML文件(loaders: {test: /\.html/, loader: 'html'}
),在模块JavaScript文件中定义一个名为myTemplate
的组件:
import myTemplate from './my-template.html';
angular.module(...)
.component('myTemplate', {template: myTemplate})
之后使用它:
<my-template></my-template>
дҪ еҸҜд»ҘдҪҝз”ЁHTMLеҠ иҪҪеҷЁе’ҢAngularзҡ„$templateCacheжңҚеҠЎ
angular
.module('template',[])
.run(['$templateCache', function($templateCache) {
var url = 'views/common/navigation.html';
$templateCache.put(url, require(url));
}]);
webpack加载器配置:
{
test: /\.html$/,
loader: 'html',
query: {
root:sourceRoot
}
}
//@require "./**/*.html"
而在您的模板中,您可以使用
<div ng-include="'my-template.html'"></div>
ng-include
指令中不需要相对路径,因为通过在入口文件头部添加//@require
命令来处理这个问题。"'template-name.html'"
,而不是"template-name.html"
或者'template-name.html'
。
如何配置加载器
我已经在https://stackoverflow.com/a/34815472/833093上发布了这个问题:
要启用,您必须配置“relativeTo”参数,否则您的模板部分将加载到“/home/username/path/to/project/path/to/template/”(检查您的bundle.js,您可能会在项目中泄漏您的用户名)。
var ngTemplateLoader = (
'ngtemplate?relativeTo=' + path.resolve(__dirname, './src/') +
'!html'
);
module.exports = {
...
module: {
loaders: [
{test: /\.html$/, loader: ngTemplateLoader},
],
},
...
}
那么在您的代码中,只需进行一个副作用的 require:
// src/webapp/admin/js/foo.js
require('../../templates/path/to/template.html');
然后你可以加载HTML:
<div ng-include src="'/webapp/templates/path/to/template.html'"</div>