2017-08-07 111 views
0

編輯:我還沒有找到一種方法來導入模板與import聲明而不是require,但我發現我可以簡化我的配置。用AngularJS + Webpack2包含模板的最佳方式是什麼?

在webpack配置中,使用html-loader而不是ngtemplate-loader代替/\.html$/。然後,在組件中,像在原始文章中那樣需要文件頂部的模板,但在組件定義中將「templateUrl」更改爲「模板」。 Webpack將爲您完成剩下的工作。

const template = require('./component.html'); 

class Example(){ 
    ...  
} 

export const component = { 
    bindings: {}, 
    controller: Example, 
    template: template 
}; 

原帖:

我有ngtemplate-loader一個有效的解決方案:

const template = require('./component.html'); 
import ExampleService from './example.service'; 

class Example() { 
    constructor(private exampleService: ExampleService) { 

    } 
    ... 
} 

export const component = { 
    bindings: {}, 
    controller: Example, 
    templateUrl: template 
}; 

但我怕我的同事們會反對require語法。你看,我正在將我們的應用從Grunt遷移到Webpack2,而目前的應用只使用import foo from './bar'語法。

我們也不會在當前版本的javascript文件中導入模板;我們在templateUrl中使用回調來返回一個字符串。

import ExampleService from './example.service'; 

class Example() { 
    constructor(private exampleService: ExampleService) { 

    } 
    ... 
} 

export const component = { 
    bindings: {}, 
    controller: Example, 
    templateUrl: ['constantsFactory', function(constantsFactory) { 
     return `${constantsFactory.path}/component.html`; 
    }] 
}; 

是否有一個的WebPack加載器可以填充$ templateCache沒有require

如果不是,有沒有辦法用import語法在Typescript中導入模板?

+0

這是爲angular2 +? – Ero

+0

不,這是用於AngularJS(特別是1.5.7) – user2954463

回答

0

沒有辦法通過使用import語法將模板添加到$ templateCache,但可以使用'require'語法將模板添加到緩存。

angular1-templateurl-loader

我能找到現在的最佳裝載機。

相關問題