我试图在我的反应应用程序中有两个不同的样式文件来支持 RTL 和 LTR 方向。因此,我使用 RTLCSS 及其 Webpack 插件来生成两个不同的文件:(myfile.chunk.css 和 myfile.chunk.rtl.css)。
但是,在 HtmlWebpackPlugin 生成的 index.html 文件中,注入了其中之一。如何拥有两个索引文件,如 index.html 和 index.rtl.html?第二个文件应包含 RTL 样式文件,包括 RTL 块。
我试图在我的反应应用程序中有两个不同的样式文件来支持 RTL 和 LTR 方向。因此,我使用 RTLCSS 及其 Webpack 插件来生成两个不同的文件:(myfile.chunk.css 和 myfile.chunk.rtl.css)。
但是,在 HtmlWebpackPlugin 生成的 index.html 文件中,注入了其中之一。如何拥有两个索引文件,如 index.html 和 index.rtl.html?第二个文件应包含 RTL 样式文件,包括 RTL 块。
要完成您正在寻找的内容,请首先阅读插件文档:
现在,要控制生成的 HTML,您需要注意添加到HtmlWebpackPlugin
配置中的任何其他键都可以通过htmlWebpackPlugin.options
.
例如,将dir
密钥添加到配置:
webpack.config.js
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template',
// Load a custom template (lodash by default)
template: 'index.template.html',
// Extra Key
dir:'rtl'
})
]
可以通过以下方式在我们的模板中访问htmlWebpackPlugin.options.dir
:
index.template.html
<!DOCTYPE html>
<html dir="<%=htmlWebpackPlugin.options.dir%>">
<head>
<meta charset="utf-8"/>
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- print a list of all available keys -->
<pre>
<%=JSON.stringify(htmlWebpackPlugin)%>
</pre>
</body>
</html>
话虽如此,我们可以切换到手动资产注入,以更好地控制页面中包含哪些 CSS 文件,例如,myproject.rtl.css
而不是myproject.css
webpack.config.js
plugins: [
new HtmlWebpackPlugin({
.
.
.
// disable automatic injection of assets
inject: false,
})
]
index.template.html
<!DOCTYPE html>
<html dir="<%=htmlWebpackPlugin.options.dir%>">
<head>
<meta charset="utf-8"/>
<title><%= htmlWebpackPlugin.options.title %></title>
<!-- manually inject css -->
<%=
Object.keys(htmlWebpackPlugin.files.chunks).map(
key => htmlWebpackPlugin.files.chunks[key].css.map(
css=>`<link href="${htmlWebpackPlugin.options.dir == 'rtl' ?css.replace('.css','.rtl.css'):css}" rel="stylesheet">`)
.join(''))
.join('')
%>
</head>
<body>
<!-- print a list of all available keys -->
<pre>
<%=JSON.stringify(htmlWebpackPlugin)%>
</pre>
<!-- manually inject js -->
<%=
Object.keys(htmlWebpackPlugin.files.chunks).map(
key=>`<script type="text/javascript" src="${htmlWebpackPlugin.files.chunks[key].entry}" defer></script>`)
.join('')
%>
</body>
</html>
应用上述内容将使您能够生成index.ltr.html
并且index.rtl.html
无需硬编码捆绑引用。