2017-05-02 62 views
0

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

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

然而,这意味着它是乏味的最好改变的标记,因为我必须去通过捆绑过程需要〜5-10秒,我的机器上。 我想要的是在生产版本上保留模板上的需求,但在开发过程中有一个模板url,所以我可以更改标记而不必捆绑。但是当创建产品包时,所有模板都内联到包中。

有没有办法做到这一点?最好的方法是创建我自己的webpack插件吗?这样不存在吗?

问候 莫滕

回答

0

我结束了创建我自己的的WebPack装载机使用正则表达式来搜索并替换模板:(“ some.html”)要求与templateUrl指向的文件同一文件夹。适用于Mac和Windows。唯一的要求是打字稿文件和html文件都需要在同一个文件夹中。这只会应用于您不希望每次更改标记文件时都要运行webpack的开发版本。对于prod,require将仍然内联在该包中的模板中。

我的装载器的内容看起来像下面的代码。挂起作为一个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; 
}