How can I inject a build number with webpack?

后端 未结 7 973
野的像风
野的像风 2021-01-30 10:38

I\'d like to inject a build number and version information to my project as it\'s built with webpack. For example, so that my code can do something like:

var bui         


        
7条回答
  •  暖寄归人
    2021-01-30 10:59

    I couldn't get this to work with TypeScript, so I helped myself by creating a file upon every compilation.

    webpack.config.js

    const fs = require('fs'); 
    const path = require('path'); 
    fs.writeFileSync(path.resolve(path.join(__dirname, 'src/version.ts')), 
    `// This file is auto-generated by the build system. 
    const BundleVersion = "${ new Date().toISOString().substr(0, 10) }"; 
    export default BundleVersion; 
    `); 
    

    Then I just import BundleVersion from './version'; and make sure it actually gets used somewhere (console.log or exposing it somewhere), so it is not being tree-shaken out, and that's it, timestamp (or version) in the bundle, created at compilation time (straight forward from here to read the package.json and use the package version if needed).

提交回复
热议问题