npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

version-check-webpack-plugin

v1.2.2

Published

A webpack plugin to generate dynamic-version json file and inject version-check function into frontend dist assets. 一个用于给前端代码动态生成版本json文件和注入检测版本脚本的Webpack插件。

Downloads

15

Readme

version-check-webpack-plugin

A webpack plugin to generate dynamic-version json file and inject version-check function into frontend dist assets. 一个用于给前端代码动态生成版本json文件和注入检测版本脚本的Webpack插件。

Usage

npm install version-check-webpack-plugin --save-dev / yarn add version-check-webpack-plugin -D

Options

interface Options { versionFilename?: string, entryNeedInjectedUpdater?: string | [] }
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const VersionCheckPlugin = require('version-check-webpack-plugin');
/**
 * @type {import('webpack').Configuration}
 */
const webpackConfig = {
    mode: 'production',
    context: path.resolve(__dirname, './'),
    entry: {
        main: {
            import: ['./src/index.js']
        },
        vendor: './src/vendor.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist/'),
        filename: '[name].[chunkhash:8].js',
        publicPath: '/public'
    },
    plugins: [
        new VersionCheckPlugin({
            versionFilename: 'version/current-version.json',
            // entryNeedInjectedUpdater: ['main'], // or next line
            entryNeedInjectedUpdater: 'main'
        }),
        new HTMLWebpackPlugin({
            filename: 'index.html',
            template: path.resolve(__dirname, 'index.html'),
            inject: 'body'
        })
    ]
};
module.exports = webpackConfig;

HTMLWebpackPlugin is recommended with this plugin.

Dist Assets like:

dist/version/current-verion.json

{"version":"e3131e0662c4c2dc9c5b37fab2dbf6e1329fb50134ad6cdad81722e54c68"}

version-check code like(just origin template, not transformed yet):

function initial(self) {
    const cvkey = `__${(0xbc729ba02bd1).toString(36)}_version-check-updater__`;
    const previousVersion = self.localStorage.get(cvkey);
    if (previousVersion === null) {
        fetchVersion().then(versionJson => {
            self.localStorage.setItem(cvkey, versionJson.version);
        }).catch(e => {
            console.warn(`Do initial check version failed cause: ${e.message || e.toString()}`);
        })
    }

    /**
     * Get latest version.
     * @returns {Promise<{version: string}>}
     */
    function fetchVersion() {
        return new Promise((resolve, reject) => {
            fetch(`{{versionHashPath}}?tag=${Math.random().toString(36).slice(2)}`, {
                credentials: 'include',
                method: 'GET',
            }).then(res => {
                res.json().then(versionJson => resolve(versionJson));
            }).catch(e => reject(e));
        });
    }

    /**
     * Check if new version built.
     * @param {boolean} forceRefresh 
     * @returns {Promise<boolean>}
     */
    function versionCheckController(forceRefresh) {
        return new Promise((resolve, reject) => {
            fetchVersion().catch(e => reject(e)).then(versionJson => {
                if (versionJson.version === previousVersion) resolve(false);
                else if (forceRefresh) self.location.reload();
                else resolve(true);
            })
        });
    }

    self.$versionCheckController = versionCheckController;

    return versionCheckController;
}

export default initial(globalThis || window);

And in entry index.html this script will be injected like:

<script defer="defer" src="/public/updater.34ad6cda.js"></script>

So you can use it like:

//...

function doUdpate() {
    $versionCheckController(/** forceRefresh */false).then(verionChanged => {
        if (versionChanged) {
            //TODO 
            // show version changed message for user fetch new version or reload window directly ^_^
        }
    })
}
function beforeRouteChange() {
    doUdpate();
}

request('/api/list/detail?id=12').then(res => {
    if (res.status === '404') doUdpate();
}).catch(e => {
    doUdpate()
})
//...