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

2024-05-06

我正在构建一个同构应用程序。 它完全是用react构建的——也就是说,html基础也在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,但让我的节点服务器提供哈希文件。

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


The ExtendedAPIPlugin https://github.com/webpack/docs/wiki/list-of-plugins#extendedapiplugin adds a __webpack_hash__变量到你的包中,这可能就是你正在寻找的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Webpack 进行缓存,索引源代码中的 [hash] 值,使用 React.js 的相关文章

随机推荐