Mar
Mar

Reputation: 1606

how to import html files with webpack 2?

I can't figure out how to import html files with webpack 2! I am using angular 1.6.0 and typescript.

I would like to import a template and use it as a router state template:

import * as angular from 'angular';
import * as uiRouter from 'angular-ui-router';
import theView from './theView.html';
import appComp from './app.component';

export default angular
    .module('app.main', [uiRouter]) 
    .component('myAppComp', appComp)
    .config(($stateProvider, $urlRouterProvider, $locationProvider) => {
    'ngInject';
    $locationProvider.hashPrefix('');

    $stateProvider
        .state('main', {
            url: '/main',
            template: '<p>main state template</p>'
        })
        .state('main.cardList', {
            url: '/cardList',
            template: theView 
        });
}

It gives:

error: 
    ERROR in ./src/app/module.ts
    (3,22): error TS2307: Cannot find module './theView.html'.

What (wierd) I don't understand is if I import the template same as above and use it in a component template, it does gives same error "cannot find module './theView.html'" but it works!

This works (with ts compilation error):

import template from './theView.html';

.component(appComp, {
    template
})

webpack.config:

module.exports = {
    entry: './src/app/module.ts',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.html$/,
                use: [{ loader: 'html-loader' }]
            }

        ]
    },
    output: {
        filename: 'bundle.js',
        path: __dirname + "/dist"
    }
};

What is going on here..?

Upvotes: 2

Views: 981

Answers (1)

Mar
Mar

Reputation: 1606

For the people who can come across this problem in the future; it is solved as follows:

declare const require: any;

$stateProvider 
    .state('main.cardList', {
        url: '/cardList',
        template: require('./theView.html').default
    });

Credits to @yadejo for the answer above!

Upvotes: 1

Related Questions