如何在js模块代码中获取带有哈希值的webpack输出文件名?

时间:2019-01-04 11:25:57

标签: javascript webpack

Polyfill是一个JS库,可消除浏览器之间js实现的差异。此处的测试过程是在浏览器不支持fetch的情况下将polyfill的脚本添加到标签中以支持fetch。如何获取生成的webpack版本带有哈希值的polyfiles.js文件名?

webpack.config.js文件内容:

const path = require('path');
module.exports = {
    entry: {
        app: './src/index.js',
        another: './src/another.js',
                polyfills: './src/polyfills.js'
    },
    output: {
        **filename: '[name].[chunkhash].js',**
        path: path.resolve(__dirname, 'dist')
    }
}

index.js文件内容:

import 'babel-polyfill';
var modernBrowser = (
    'fetch' in window && 
    'assign' in Object
);

if (!modernBrowser) {
    var scriptElement = document.createElement('script');

    scriptElement.async = false;
    **scriptElement.src = './polyfills.js';**

    document.head.appendChild(scriptElement);
}

fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => {
        console.log('We retrieved some data! AND we\'re confident it will work on a variety of brower distributions.');
        console.log(json);
    })
    .catch(error => console.error('Something went wrong when when fetching this data: ', error));

预期结果:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Production</title>
        **<script src="polyfills.03c614b6256ac2293323.js"></script>**
    </head>
    <body>
        <script src="app.d7fb858ab050773be201.js" type="text/javascript"></script>
        <script src="another.afe2eeac5ed9fc767a52.js" type="text/javascript"></script>
        <script src="polyfills.03c614b6256ac2293323.js" type="text/javascript"></script>
    </body>
</html>

实际结果:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Production</title>
        **<script src="./polyfills.js"></script>**
    </head>
    <body>
        <script src="app.d7fb858ab050773be201.js" type="text/javascript"></script>
        <script src="another.afe2eeac5ed9fc767a52.js" type="text/javascript"></script>
        <script src="polyfills.03c614b6256ac2293323.js" type="text/javascript"></script>
    </body>
</html>

0 个答案:

没有答案