原因猜想:使用html-loader加载了两次html

比如,错误示例:

    module: {
        rules: [
            // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
            {test: /\.ts$/, loader: "ts-loader"},
            {test: /\.(html)$/, loader: "html-loader"},
            {test: /\.html/, loader: "html-loader"}
        ]
    },

则在代码中看到require('./yunzhi.html')时。首先,由于符合第一条 {test: /\.(html)$/, loader: "html-loader"},则将html编译为变量A -> (module.exports);然后,由于再次符合第二条规则{test: /\.html/, loader: "html-loader"},又重新将A进行了二次编译,然后就出现了我们不想看到的。

例子

a.html

<yunzhi></yunzhi>

yunzhi组件

app.component('yunzhi', {
    template: require('./yunzhi.html')
    ...
});

yunzhi.html

<h1>hello</h1>
<h2>hello</h2>

则发生如下错误:

clipboard.png

解决方案

删除冗余的loader
删除前:

    module: {
        rules: [
            // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
            {test: /\.ts$/, loader: "ts-loader"},
            {test: /\.(html)$/, loader: "html-loader"},
            {test: /\.html/, loader: "html-loader"}
        ]
    },

删除后:

    module: {
        rules: [
            // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
            {test: /\.ts$/, loader: "ts-loader"},
            {test: /\.(html)$/, loader: "html-loader"},
        ]
    },

潘杰
3.1k 声望238 粉丝