使用React.js在Webpack中使用[hash]值缓存索引源代码

Fed*_*ico 6 caching node.js reactjs webpack isomorphic-javascript

我正在构建一个同构的应用程序.它是完全建立的反应 - 即,HTML基地也在反应.

我有我的根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;
Run Code Online (Sandbox Code Playgroud)

当我使用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;
Run Code Online (Sandbox Code Playgroud)

理想情况下,将正确的哈希引用注入到构建的js中.

它有点棘手,因为它是自引用的.有没有更好的方法呢?在webpack完成后修改构建的代码似乎适得其反.我还想过让客户端简单地请求bundle.js,但让我的节点服务器提供散列文件.

什么是这个缓存的正确解决方案?

Ale*_*erg 7

ExtendedAPIPlugin增加了一个__webpack_hash__变量的捆绑,这可能是你在找什么.


Fed*_*ico 4

我发现最好的解决方案是将 webpack 资源传递到应用程序中,而不是尝试在应用程序中渲染它。这可以直接通过 props 实现,也可以通过 Flux 实现。

这样你的代码就可以用变量来呈现。变量的值与构建过程无关。

...
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;
Run Code Online (Sandbox Code Playgroud)

类似的事情。