Import html files with es6 template template loader

I want to import my templates in js with the es6 template template loader . The only difference in my case is that I do not want to include css, only html. My code is as follows:

import app from '../../bootstrap.js'; import template from './header.html'; app.component('siteHeader', { template }); 

and my error is Uncaught SyntaxError: Unexpected token export .

+8
javascript webpack
source share
5 answers

I just had to do the same thing recently, and that's exactly how I did it.

1. I used the npm html-loader module instead of es6-template-string-loader

2. Add to webpack.config.js

Webpack 3

 ... module: { rules: [ { test: /\.html$/, exclude: /node_modules/, use: {loader: 'html-loader'} } ] } ... 

Webpack 1 (deprecated, but from the original answer):

 ... module: { loaders: [ { test: /\.html$/, loader: "html-loader" } ] } ... 

3. Use in your JS files

 import template from './header.html'; 
+14
source share

Consider using the Raw Bootloader .

Your web package configuration will contain the following:

 ... module: { rules: [ { test: /\.tpl.html$/, use: 'raw-loader' } ] } ... 

In the code, enter

 import tpl from './mytemplate.html'; 
+2
source share

I am assuming your webpack.config.js matches the following lines:

 ... module: { loaders: [ { test: /\.html$/, loader: "es6-template-string" } ] } ... 

The problem is that template-string-loader outputs the exported template string using ES6 syntax. You still need to pass this 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 as a function:

 import app from '../../bootstrap.js'; import template from './header.html'; app.component('siteHeader', { template() }); 
+1
source share

Try

 module: { loaders: [ { test: /\.html$/, loader: 'html-loader?exportAsEs6Default', } ] } 

You can read more about this configuration syntax in the html-loader repo readme

https://github.com/webpack-contrib/html-loader#export-formats

0
source share

I would use raw-loader instead of text-loader , because it has many more contributors, and it is officially mentioned in the documentation for the web package: https://webpack.js.org/loaders/raw-loader/

This is a safer choice in 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 the template file as a string for my components, for example:

 import Vue from 'vue' import MyTemplate from './template.tpl' Vue.component('my-component',{ 'template' : MyTemplate }) 
0
source share

All Articles