[英]Importing html files with es6 template string loader
我想使用es6 template string loader將我的模板導入到我的 js 中。 在我的情況下唯一的區別是我不想包含 css,只包含 html。 我的代碼如下:
import app from '../../bootstrap.js';
import template from './header.html';
app.component('siteHeader', {
template
});
我的錯誤是Uncaught SyntaxError: Unexpected token export
。
我最近需要做同樣的事情,我就是這樣做的。
1.我使用了 npm 模塊html-loader
,而不是es6-template-string-loader
2.添加到webpack.config.js
...
module: {
rules: [
{
test: /\.html$/,
exclude: /node_modules/,
use: {loader: 'html-loader'}
}
]
}
...
...
module: {
loaders: [
{
test: /\.html$/,
loader: "html-loader"
}
]
}
...
3.在你的JS文件中使用
import template from './header.html';
此處發布的解決方案是正確的。 只需向我在實施提到的解決方案時遇到的錯誤添加信息。
我收到錯誤:TS2307:找不到模塊“./index3.html”
這是因為打字稿編譯錯誤。 解決辦法就在這里
必須定義一個文件:包含以下內容的 html.d.ts
declare module '*.html' {
const value: string;
export default value
}
考慮使用Raw Loader 。
您的 webpack 配置將包含以下內容:
...
module: {
rules: [
{
test: /\.tpl.html$/,
use: 'raw-loader'
}
]
}
...
在你的代碼中寫
import tpl from './mytemplate.html';
我假設你的webpack.config.js
是這樣的:
...
module: {
loaders: [
{
test: /\.html$/,
loader: "es6-template-string"
}
]
}
...
問題是template-string-loader
使用 ES6 語法輸出一個導出的模板字符串函數。 你仍然需要通過 babel 傳遞它。
您的配置應如下所示:
...
module: {
loaders: [
{
test: /\.html$/,
loader: "babel?presets[]=es2015!es6-template-string"
}
]
}
...
要使用它,您需要將其作為函數調用:
import app from '../../bootstrap.js';
import template from './header.html';
app.component('siteHeader', {
template()
});
試試
module: {
loaders: [
{
test: /\.html$/,
loader: 'html-loader?exportAsEs6Default',
}
]
}
可以在html-loader
repo readme 中閱讀有關此配置語法的更多信息
https://github.com/webpack-contrib/html-loader#export-formats
我會使用raw-loader
而不是text-loader
,因為它有更多的貢獻者,並且在 webpack 文檔中正式提到: https ://webpack.js.org/loaders/raw-loader/
從長遠來看,這是一個更安全的選擇。 下載鏈接: https : //www.npmjs.com/package/raw-loader
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(tpl|txt)(\?.*)?$/,
use: 'raw-loader'
}
]
}
}
現在,我可以使用它來加載模板文件作為組件的字符串,例如:
import Vue from 'vue'
import MyTemplate from './template.tpl'
Vue.component('my-component',{
'template' : MyTemplate
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.