【问题标题】:Load bundle from different host从不同的主机加载包
【发布时间】:2017-03-15 15:51:57
【问题描述】:

我正在使用 webpack 构建一个单页应用程序,以使用 HtmlWebpackPlugin 构建 main.<hash>.jsmain.<hash>.cssindex.html

这会将包注入index.html

<script type="text/javascript" src="/static/js/main.4d67bd1c.js"></script>

在正文中,并且

<link href="/static/css/main.f6908217.css" rel="stylesheet">

在头脑中。

如何在 href 和 src 中包含主机?我曾尝试使用带有 HtmlWebpackPlugin 的自定义模板,但我不确定如何获取已编译包 js/css 的路径。

HtmlWebpackPlugin 配置如下:

new HtmlWebpackPlugin({
    inject: true,
    template: paths.appHtml,
    minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
    }
})

(这基本上直接来自 create-react-app)

【问题讨论】:

    标签: webpack


    【解决方案1】:

    html-webpack-plugin 尊重 webpack 配置的 output.publicPath 选项。您可以设置主机的公共路径,它会自动将其添加到资产中。以这种配置为例:

    output: {
      filename: '[name].[hash:6].js',
      publicPath: 'https://myhost.com/'
    }
    

    捆绑包包含为:

    <script type="text/javascript" src="https://myhost.com/main.1ae0e6.js"></script>
    

    如果您更喜欢使用自定义模板,您可以按如下方式包含捆绑包(如在default template 中):

    <% for (var chunk in htmlWebpackPlugin.files.chunks) { %>
    <script src="<%= htmlWebpackPlugin.files.chunks[chunk].entry %>"></script>
    <% } %>
    

    您可以将您的主机添加到src。对于 CSS,请参阅 default template - CSS。在这种情况下,您还应该设置inject: false,这样就不会再次添加它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多