如何在一个WordPress站点中使用PHP来查找散列的bundle.js文件并将相应的文件名插入到脚本标记中?

问题描述:

所以,我从来没有写过PHP,直到今天,我正试图在一个wordpress网站上实现一个缓存破解系统,这个系统里面有一些React组件。所以footer-home.php文件里我有这样的:如何在一个WordPress站点中使用PHP来查找散列的bundle.js文件并将相应的文件名插入到脚本标记中?

 </div> <?php // close #app ?> 
    </main> 
    <div class="container footer"> 

    <div class="row"> 
     <div class="col-sm-12"> 
     <div id="instagram"></div> 
     </div> 
    </div> 

    <?php get_footer('shared') ?> 
    </div> 

    </div><?php //close container ?> 

<?php 
function grab_hashed_bundle_script() { 
    $path = '/client/'; 
    $fileName = null; 
    $dirJS = new DirectoryIterator($path); 

    foreach ($dirJS as $file) { 
    if (pathinfo($file, PATHINFO_EXTENSION) === 'js') { 
     $fileName = basename($file); 
     break; 
    } 
    } 
    return $fileName; 
} 

$bundle_js = grab_hashed_bundle_script(); 
?> 
    <script src="/client/<?php echo $bundle_js ?>"></script> 
    <?php wp_footer(); ?> 
</body> 
</html> 

我知道这是丑陋的AF和哈克,因此,如果任何人都可以指出一个更好的方式来做到这一点,我所有的耳朵。

我需要这样做的原因是我每次运行新版本时,都会在webpack中为bundle.js文件名添加一个随机的6位散列值(如bundle-123456.js)。之前,我们在这个页脚文件中只有一个常规脚本标记,如下所示: <script src=/client/bundle.js"></script>但客户端的浏览器即使在更新之后也会缓存bundle.js,因此客户必须清空缓存才能获得新的缓存。 js文件。

任何帮助,非常感谢。

此外,我不试图缓存与评论中建议的参数缓冲区。我试图基于随机哈希来破坏我正在构建时将webpack插入到bundle.js文件的名称中。

+0

的[缓存清除通过PARAMS](可能的复制https://stackoverflow.com/问题/ 9692665/cache-busting-via-params) –

+0

根本不是我想要做的。我试图在wordpress模板中处理这个问题,而不是在服务器文件系统中 –

+1

您无法在客户端创建相同的随机6位数字。您必须更改服务器上的JS文件。有一些技巧,如[ETAG,过期或年龄](https://stackoverflow.com/questions/499966/etag-vs-header-expires)。否则,您可以使用@ James的回答来避免缓存。无论如何,你必须停止在文件名中添加随机数。它根本没有帮助。 – Buaban

这是解决我的同事之一想出了:

内的functions.php

/** 
* Grab Hashed Bundle Files 
*/ 

function enqueue_hashed_bundle_files() { 
    // soooo gross. would love to know of a cleaner way. 
    $build_dir = get_theme_root() . '/../../../client/build/'; 
    $all_files = scandir($build_dir); 

    $css_files = array(); 
    $js_files = array(); 

    foreach($all_files as $file){ 
    $pathinfo = pathinfo($file); 
    switch($pathinfo['extension']){ 
     case 'js': 
     array_push($js_files, $file); 
     break; 
     case 'css': 
     array_push($css_files, $file); 
     break; 
     default: 
     break; 
    } 
    } 

    // now that we have the filenames, we can access them directly with the 
    // absolute url 

    $base_url = get_option('siteurl') . '/client/'; 

    wp_enqueue_script('bundlejs', $base_url . $js_files[0], array(), null, true); 
    wp_enqueue_style('bundlecss', $base_url . $css_files[0], array(), null); 
} 

更改您对js文件的请求,使其具有查询参数,而不是文件名中的随机字符串。

请参阅this后。浏览器不应该使用查询字符串来缓存它。

+1

我们通常只是追加一个时间戳 –

+0

如果你建议解决方案是缓存破坏只是这样说,并提供一些代码示例,提供链接只有答案很可能会得到版主的注意 – svarog