角度组件中的条件模板或模板URL

时间:2017-05-02 11:11:37

标签: angular webpack require

说我有以下组件。使用webpack将它捆绑在一起。该模板是必需的,因此它是内联的。

@Component({
    selector: 'date-picker',
    template: require('./date-picker.html'),
})

然而,这意味着更改标记很繁琐,因为我必须完成捆绑过程,最多只需要5-10秒。 我想要的是在生产版本上保留模板上的需求,但在开发期间有一个模板URL,这样我就可以更改标记而无需捆绑。但是,在创建生产包时,所有模板都会内联到包中。

有没有办法让这种情况发生?最好的方法是创建我自己的webpack插件吗?这种情况不存在吗?

祝你好运 的Morten

1 个答案:

答案 0 :(得分:0)

我最终为Webpack创建了自己的加载器,使用正则表达式来搜索并替换模板:require(' .some.html'),其中templateUrl指向该文件同一个文件夹。适用于mac和windows。唯一的要求是typescript文件和html文件都需要在同一个文件夹中。这只适用于您每次更改标记文件时都不想运行webpack的开发版本。对于prod,require仍然会在bundle中嵌入模板。

我的加载程序的内容最终看起来像下面的代码。作为webpack加载器被绑定。Documentation for loaders in webpack

/*
This loader can replace template: require to templateUrls for angular components as long as they live inside the 
same folder as the component itself. This is in particular very useful for development builds to avoid having to 
run webpack everytime you change an html file.
*/

module.exports = function(source) {

//If there's no match, we're not processing a Component file.
var groups = source.match(`template: require\\('.*.html.*'\\)`);
if (groups == null)
{
    return source;
}


var resourcePath = this.resourcePath;
var regex = new RegExp(/\//g);

//To support OSX and win paths we replace / which is part of OSX paths to process the same way.
resourcePath = resourcePath.replace(regex,'\\');

//Find a relative path to the resource relative to the apps folder.
var relativePathForAppsFolder = resourcePath.substr(resourcePath.indexOf('\\app\\'))
relativePathForAppsFolder = relativePathForAppsFolder.replace(/\\/g,'/');

//Get the path without the filename to support html files and js files not sharing the same name minus the extension.
var pathWithoutFolder = relativePathForAppsFolder.substr(0, relativePathForAppsFolder.lastIndexOf('/'))


//To support having different names on the file and ts file we take the content of the group in our regex which would be the html file name.
var matchedString = groups[0].split('\''); 
var value = matchedString[1];  
value = value.replace('./','');
var combined = pathWithoutFolder + '/' + value;

//now we're changing to template url for dev builds instead of inline inside webpack bundle.
source = source.replace(/template: require\('.*.html.*'\)/,'templateUrl: \'' + combined + '\'')
return source;
}