webpack html 模板插值,使用HTML Webpack插件的部分错误

kite.js.org..

10

编辑

(编辑:2017-12-20将"装载机"移至"规则")

默认情况下,"html-webpack-plugin"将模板解析为" 下划线 "(也称为lodash)模板,您的"template.html"没有错,错误是由webpack无法为您解析'html-loader' "template.html"

,所以你需要为webpack安装"html-loader",并配置它:

在命令行中:

npm install html-loader

并为webpack配置,编辑webpack.config.js:

...

module: {

rules: [

// ...

{

test: /\.html$/, // tells webpack to use this loader for all ".html" files

loader: 'html-loader'

}

]

}

到现在你可以运行"webpack"你会看到没有错误,但生成的"index.html"不是你想象的,因为你的模板文件有".html"扩展名,webpack现在使用"html-loader"加载" template.html"而不是默认"lodash loader",为了解决这个问题,您可以将"template.html"重命名为"template.html.ejs"(或任何其他扩展名),以使"html-webpack-plugin"回退.除了"template.html"之外还有一点点变化,删除"html-loader!" 从中:

现在它应该工作.

编辑发布我的代码以供参考:

/src/template.html.ejs

test

template

/src/footer.html

this is a footer

/webpack.config.js

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

let config = {

entry: {

index: './src/js/index'

},

output: {

path: path.resolve(__dirname, 'dist'),

filename: '[name].js'

},

module: {

rules: [

{

test: /\.html$/,

loader: 'html-loader'

}

],

},

plugins: [

new HtmlWebpackPlugin({

template: './src/template.html.ejs'

})

]

}

module.exports = config;

/package.json

{

"name": "test",

"version": "1.0.0",

"description": "",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "",

"license": "ISC",

"dependencies": {

"html-loader": "^0.5.1",

"html-webpack-plugin": "^2.30.1",

"webpack": "^3.10.0"

}

}

/src/js/index.js

console.log("A test page!");

环境:

webpack 3.10.0

npm 5.6.0

运行webpack后"/dist/index.html"的内容:

test

template

this is a footer

正如您所见,"footer.html"的内容已正确插入.

老答复

安装"html-loader" npm install html-loader

将"html-loader"添加到"webpack.config.js"以加载扩展名为".html"的文件,如:

module: {

rules: [{

test: /\.html$/,

loader: 'html-loader'

}],

}

添加interpolate标志以启用ES6模板字符串的插值语法,如下所示:

plugins: [

new HtmlWebpackPlugin({

template: '!!html-loader?interpolate!src/template.html'

})

]

修改您template.html的匹配ES6模板:

template

${require('./footer.html')}

跑webpack,它会工作

方法2:使用"下划线"模板

按照"方法1"步骤1和2,然后:

将"template.html"重命名为"template.html.ejs"

切换template: './src/template.html'到template: './src/template.html.ejs'"webpack.config.js"

运行webpack

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值