使用 Webpack 为 RTL 和 LTR 支持生成两个不同的索引文件

Generate two different index files for RTL and LTR support using Webpack

我正在尝试在我的 React 应用程序中使用两个不同的样式文件来支持 RTL 和 LTR 方向。因此,我使用 RTLCSS 及其 Webpack 插件生成两个不同的文件:(myfile.chunk.css 和 myfile.chunk.rtl.css)。

但是,在HtmlWebpackPlugin生成的index.html文件中,注入了其中一个。我怎样才能有两个索引文件,如 index.html 和 index.rtl.html? 第二个文件应包含 RTL 样式文件,包括 RTL 块。

要完成您要查找的内容,请先阅读以下插件文档:

  1. Generating Multiple HTML Files
  2. Writing Your Own Templates.

现在,要控制您生成的 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.htmlindex.rtl.html 而无需硬编码包引用。