小编典典

使用Webpack进行缓存,使用React.js在索引源代码中填充[hash]值

reactjs

我正在构建同构应用程序。它是完全由react构建的-即html base也处于react中。

我将根html作为应用程序组件。

看起来像这样:

...
var AppTemplate = React.createClass({
    displayName: 'AppTemplate',
    render: function() {
        return (
            <html>
                    <head lang="en">
                        <title>hello</title>
                        <link rel="stylesheet" href='/css/style.css' />
                    </head>
                    <body>
                        <RouteHandler {...this.props}/>
                        <script type='text/javascript' src='/js/bundle.js' />
                    </body>
                </html>
        );
    }
});
...
module.exports = AppTemplate;

当我使用webpack构建项目时,我需要替换js / bundle.js以包括哈希值。

完成后,Webpack将交付stats.json。但是我需要在构建期间使用哈希。

我当时正在考虑使用功能标记来执行以下操作:

...
var AppTemplate = React.createClass({
    displayName: 'AppTemplate',
    render: function() {
        return (
            <html>
                    <head lang="en">
                        <title>hello</title>
                        <link rel="stylesheet" href='/css/style.css' />
                    </head>
                    <body>
                        <RouteHandler {...this.props}/>
                        <script type='text/javascript' src='/js/bundle.{__HASH__}.js' />
                    </body>
                </html>
        );
    }
});
...
module.exports = AppTemplate;

理想情况下,它将正确的哈希引用注入到内置的js中。

因为它是自引用的,所以有点棘手。有更好的方法吗?在webpack完成后修改构建的代码似乎适得其反。我还考虑过让客户端仅请求bundle.js,但让我的节点服务器提供哈希文件。

什么是此缓存的适当解决方案?


阅读 169

收藏
2020-07-22

共1个答案

小编典典

我发现最好的解决方案不是尝试在应用程序中呈现它,而是将Webpack资产传递到应用程序中。这可以直接通过道具或通过通量来实现。

这样,您的代码将使用变量呈现。变量的值与构建过程无关。

...
var AppTemplate = React.createClass({
    displayName: 'AppTemplate',
    render: function() {
        return (
            <html>
                    <head lang="en">
                        <title>hello</title>
                        <link rel="stylesheet" href='/css/style.css' />
                    </head>
                    <body>
                        <RouteHandler {...this.props}/>
                        <script type='text/javascript' src={this.props.jsFile} />
                    </body>
                </html>
        );
    }
});
...
module.exports = AppTemplate;

这样的事情。

2020-07-22