I want to import my templates into my js with es6 template string loader. The only difference in my case is that I don\'t want to include css, only html. My code is as follo
The solution posted here is correct. Just adding an info to the error i faced when implementing the solution mentioned.
I got the error: TS2307: Cannot find module './index3.html'
This was because of typescript compilation error.
The work around was here
Had to define a file: html.d.ts containing the below
declare module '*.html' {
const value: string;
export default value
}
I recently needed to do the same thing, and this is how I did it.
1. I used the npm module html-loader, instead of es6-template-string-loader
2. Add to webpack.config.js
...
module: {
rules: [
{
test: /\.html$/,
exclude: /node_modules/,
use: {loader: 'html-loader'}
}
]
}
...
...
module: {
loaders: [
{
test: /\.html$/,
loader: "html-loader"
}
]
}
...
3. Use in your JS files
import template from './header.html';
Try
module: {
loaders: [
{
test: /\.html$/,
loader: 'html-loader?exportAsEs6Default',
}
]
}
More info on this config syntax can be read in html-loader
repo readme
https://github.com/webpack-contrib/html-loader#export-formats
I would use raw-loader
instead of text-loader
, because it has much more contributors and it's officially mentioned on the webpack documentation: https://webpack.js.org/loaders/raw-loader/
It's a safer choice on the long run. Download link: https://www.npmjs.com/package/raw-loader
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(tpl|txt)(\?.*)?$/,
use: 'raw-loader'
}
]
}
}
Now, I can use it to load a template file as a string for my components, like:
import Vue from 'vue'
import MyTemplate from './template.tpl'
Vue.component('my-component',{
'template' : MyTemplate
})
Consider using Raw Loader.
Your webpack configuration will contain this:
...
module: {
rules: [
{
test: /\.tpl.html$/,
use: 'raw-loader'
}
]
}
...
In your code write
import tpl from './mytemplate.html';
I assume your webpack.config.js
is along the lines of this:
...
module: {
loaders: [
{
test: /\.html$/,
loader: "es6-template-string"
}
]
}
...
The problem is that template-string-loader
outputs an exported template string function using ES6 syntax. You'll still need to pass that through babel.
Your configuration should look something like this:
...
module: {
loaders: [
{
test: /\.html$/,
loader: "babel?presets[]=es2015!es6-template-string"
}
]
}
...
To use it you need to call is as a function:
import app from '../../bootstrap.js';
import template from './header.html';
app.component('siteHeader', {
template()
});