使用es6模板字符串加载器导入html文件

Tom*_*ski 24 javascript webpack

我想用es6模板字符串加载器将我的模板导入到我的js中.我的唯一区别是我不想包含css,只包含html.我的代码如下:

import app from '../../bootstrap.js';
import template from './header.html';

app.component('siteHeader', {
  template
});
Run Code Online (Sandbox Code Playgroud)

而我的错误是Uncaught SyntaxError: Unexpected token export.

Kev*_*Bot 33

我最近需要做同样的事情,这就是我做到的.

1.我使用了NPM模块html-loader,而不是es6-template-string-loader

2.添加到webpack.config.js

Webpack 3

...
module: {
    rules: [
        {
            test: /\.html$/,
            exclude: /node_modules/,
            use: {loader: 'html-loader'}
        }
    ]
}
...
Run Code Online (Sandbox Code Playgroud)

Webpack 1(已弃用,但原始答案):

...
module: {
    loaders: [
        {
            test: /\.html$/,
            loader: "html-loader"
        }
    ]
}
...
Run Code Online (Sandbox Code Playgroud)

3.在JS文件中使用

import template from './header.html';
Run Code Online (Sandbox Code Playgroud)

  • 在“ ./header.html”的导入模板上给出错误“找不到模块”; (2认同)

小智 6

此处发布的解决方案是正确的。只需向我在实施提到的解决方案时遇到的错误添加信息。

我收到错误:TS2307:找不到模块 './index3.html'
这是因为打字稿编译错误。解决办法就在这里

必须定义一个文件:包含以下内容的 html.d.ts

declare module '*.html' {
  const value: string;
  export default value
}
Run Code Online (Sandbox Code Playgroud)