【问题标题】:how to import html files with webpack 2?如何使用 webpack 2 导入 html 文件?
【发布时间】:2017-06-22 14:34:29
【问题描述】:

我不知道如何使用 webpack 2 导入 html 文件!我正在使用 Angular 1.6.0 和打字稿。

我想导入一个模板并将其用作路由器状态模板:

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 
        });
}

它给出:

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

什么(奇怪)我不明白的是,如果我导入与上面相同的模板并在组件模板中使用它,它确实会给出相同的错误“找不到模块'./theView.html'”但是它有效

这可行(有 ts 编译错误):

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"
    }
};

这是怎么回事..?

【问题讨论】:

  • 你能不能显示错误
  • @owaishanif786 错误很简单:找不到模块'main-view.html'
  • 你试过import * as mainView from './theView.html'吗?
  • Typescript 会寻找一个 javascript 模块,但因为它是 html 而找不到。为避免 Typescript 错误,请使用 template: require('. /theView. Html' ) 而不是 import
  • @yadejo 有帮助!谢谢!!

标签: webpack-2 webpack-html-loader


【解决方案1】:

对于将来可能遇到此问题的人;解决方法如下:

declare const require: any;

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

感谢@yadejo 上面的答案!

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2019-01-07
    • 2018-01-13
    • 2018-01-01
    • 2017-04-25
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多