EDIT: I haven't found a way to import templates with an import
statement instead of require
, but I have discovered that I can simplify my configuration.
In the webpack config, use html-loader
instead of ngtemplate-loader
for /\.html$/
. Then, in the component, require the template at the top of the file like we did in the original post, but change "templateUrl" to "template" in the component definition. Webpack will do the rest for you.
const template = require('./component.html');
class Example(){
...
}
export const component = {
bindings: {},
controller: Example,
template: template
};
original post:
I have a working solution with 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
};
But I'm afraid my colleagues will object to the require
syntax. You see, I am migrating our app from Grunt to Webpack2, and the current app only uses import foo from './bar'
syntax.
We also don't import templates in the javascript files in our current build; we use a callback in the templateUrl to return a string.
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`;
}]
};
Is there a webpack loader that can populate $templateCache without require
?
If not, is there a way to import templates in Typescript with import
syntax?
There is not a way to add templates to the $templateCache by using import
syntax, but you can add templates to the cache with 'require' syntax.
Best loader I could find right now.