是否可以将一个变量传递给我之前在'html-webpack-plugin‘中定义的’pug加载器‘加载的.pug模板?
webpack.config.babel.js
...
{
test: /\.pug$/,
use: [
{
loader: 'html-loader'
},
{
loader: 'pug-html-loader',
options: {
self: true
}
}]
}
...
plugins: [
new HtmlWebpackPlugin({
chunks: ['index'],
filename: 'index.html',
template: './src/templates/layout.pug',
title: 'Welcome',
file: 'index'
}),
new HtmlWebpackPlugin({
chunks: ['index', 'contact'],
filename: 'contact.html',
template: './src/templates/layout.pug',
title: 'Contact us',
file: 'contact'
}),
]
在layout.html中,我定义如下:
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<title><%= htmlWebpackPlugin.options.title %></title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<main>
${ require('html-loader!../partials/' + htmlWebpackPlugin.options.file + '.html' ) }
</main>
</body>
</html>
我如何使用它来传递所有变量-在Webpack插件中为我的PugTemplates和文件中的使用定义的变量?这个应用程序应该是一个简单的创建简单网页的过程,它由几个静态页面组成。
发布于 2020-01-03 08:20:35
对于那些对这个问题有困难的人。解决方案是创建一个templateGenerator
示例:
new HTMLWebpackPlugin({
inject: true,
templateParameters: paramGenerator(globals), // <--- Here
template: '/mytemplate.pug',
}),import { environment } from '../environment';
export function paramGenerator(globals: () => {[key: string]: any}) {
return (compilation, assets, assetTags, options) => {
return {
compilation: compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
tags: assetTags,
files: assets,
options: options
},
environment,
...globals(),
};
}
}其中,globals是一个函数,它返回一个附加到全局pug作用域的简单对象。
发布于 2017-07-27 10:44:35
您可以使用InterpolateHtmlPlugin替换HTML文件中的标记。
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin({
PUBLIC_URL: publicUrl
}),
...
}您可以从react-dev-utils npm包中安装插件。
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');您可以在这里看到完整的示例:
webpack配置:https://github.com/jquintozamora/react-typescript-webpack2-cssModules-postCSS/blob/master/webpack/webpack.config.dev.js#L9和https://github.com/jquintozamora/react-typescript-webpack2-cssModules-postCSS/blob/master/webpack/webpack.config.dev.js#L80-L82
package.json:https://github.com/jquintozamora/react-typescript-webpack2-cssModules-postCSS/blob/master/package.json#L55
发布于 2019-09-16 11:52:35
pug加载器options参数接受一个data属性,您可以在其中传递配置变量。见这里:
使用pug加载程序将数据传递给pug(无法读取未定义的属性)
{
loader: 'pug-html-loader',
options: {
data: {
title: 'Hello World'
}
}
}https://stackoverflow.com/questions/45347666
复制相似问题