Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing html files with es6 template string loader

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 follows:

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

and my error is Uncaught SyntaxError: Unexpected token export.

like image 942
Tomek Buszewski Avatar asked Jun 14 '16 17:06

Tomek Buszewski


People also ask

How do I import a HTML template?

Import HTMLClick Create Template. Navigate to the Code your own options and choose Import HTML. Click Browse and choose your HTML file. Name your template, and click Upload.

How do I import HTML into JavaScript?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

What is HTML loader?

The html-loader defination says that it exports html as String (What does it mean). it also says that every loadable attributes (for example <img src="image. png" is imported as require('./image. png') ,and you may need to specify loader for images in your configuration ( file-loader or url-loader ), What does it mean.


2 Answers

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

Webpack 3

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

Webpack 1 (deprecated, but from original answer):

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

3. Use in your JS files

import template from './header.html'; 
like image 123
KevBot Avatar answered Oct 06 '22 12:10

KevBot


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 } 
like image 33
Vinodh Avatar answered Oct 06 '22 12:10

Vinodh