Search code examples
typescriptknockout.jswebpackwebpack-2

Load knockout template from html file with webpack


I am trying to load my knockout templates from external files.
My setup is as follows:

  • npm
  • webpack
  • typescript

Now, I have tried a few different options but none worked:

text-loader / raw-loader / html-loader

template: require("text-loader!./my-component.html")
// or
template: require("raw-loader!./my-component.html")
// or
template: require("html-loader!./my-component.html")

Didn't work as this returns a text that resembles Javascript code with my template somewhere inside.

knockout-template-loader

template: require("knockout-template-loader!html-loader!./my-component.html")

Didn't work as it just returns an empty object.

script-template-loader

template: require("script-template-loader?addToDom=true!./hello.html")

This has two problems:

  1. template doesn't like HTMLScriptElement objects
  2. The generated script has no actual content beside the string [object Object]

require option

template: {require: "text-loader!./my-component.html"}

Didn't work as I am getting an error at runtime:

Cannot read property 'call' of undefined at __webpack_require__

What am I missing?


Solution

  • The html-loader plugin is indeed working. Why it wasn't working at first was that I registered knockout-template-loader in my webpack.config.js as the default loader for html files.
    Looks like it is using that even if a specific loader is specified in the require.
    After removing that rule, it works now