GithubHelp home page GithubHelp logo

fed / webpack-version-file Goto Github PK

View Code? Open in Web Editor NEW
24.0 2.0 8.0 336 KB

Generate a text file with your package name, deployed version and build date

Home Page: https://npm.im/webpack-version-file

License: MIT License

JavaScript 100.00%
webpack webpack-plugin

webpack-version-file's Introduction

webpack-version-file

Build Status Downloads Version License

This is a simple Webpack plugin which generates a file with your package name, version number, build date and any other details you might need. This is particularly useful as a way to know which version of your project is deployed at any given time.

Here's an example of an automatically generated version.txt file, which you can deploy next to your bundle file:

[email protected]
Build date: Mon Nov 28 2016 08:12:34 GMT+1100 (AEDT)

Installation

# npm
npm install --save-dev webpack-version-file

# yarn
yarn add --dev webpack-version-file

Setting up the plugin in your Webpack config file

Just include the module at the top of your webpack.config.js file and add a new entry to your plugins array:

const VersionFile = require('webpack-version-file');

module.exports = {
  entry: './src',
  ...
  plugins: [
    new VersionFile()
  ]
};

You can also pass in additional options:

const VersionFile = require('webpack-version-file');

module.exports = {
  entry: './src',
  ...
  plugins: [
    new VersionFile({
      output: './build/version.txt',
      package: './package.json'
    })
  ]
};

Available options are:

Option Description
output Path to the output file the plugin will generate. It defaults to ./version.txt.
package Path to the package.json file. It defaults to ./package.json.
template Path to the template file, e.g.: ./version.ejs. Has no default value.
templateString Defaults to <%= name %>@<%= version %>\nBuild date: <%= buildDate %>
data Object with additional data to be passed in to the template
verbose Log a success message to the terminal once the version file has been generated. false by default.

Custom Data

By default, within your template you have access to all of the fields in your package.json with no extra configuration, e.g.:

  • version
  • name
  • license
  • author
  • repository.url
  • etc.
<%= name %>@<%= version %>
License: <%= license %>
Author: <%= author.name %> (<%= author.email %>)

However you can also pass in custom data when you add webpack-version-file to your list of plugins:

const VersionFile = require('webpack-version-file');

module.exports = {
  entry: './src',
  ...
  plugins: [
    new VersionFile({
      data: {
        date: new Date(),
        environment: process.env.NODE_ENV || 'development'
      }
    })
  ]
};

Once you've set your custom chunks of data, you can reference them in your template by using the same name you've given them:

<%= name %>@<%= version %>
Build date: <%= date %>
Environment: <%= environment %>

Note that in this example, the only two variables coming from your package.json file are name and version. date and environment are defined in your data object.

Predefined Variables

There's a single predefined variable you can make use of: buildDate (which is also part of the default template). The plugin itself is in charge of putting this variable into scope, and its value is generated using new Date().

<%= name %>@<%= version %>
Build date: <%= buildDate %>

Custom Templates

There are two ways in which you can define your own template:

  • using a template string
  • creating a template file

In either case, the template must be written using EJS which is a JavaScript templating language. Here's a sample template:

<%= name %>@<%= version %>
Build date: <%= buildDate %>
Comments: <%= comments %>

where name and version both come from the package.json file, buildTime is a variable injected by this library and comments is a custom variable set on the webpack.config.js file as part of the data object on your plugin definition.

This template can also be written inline in case you don't want an extra file on your project. The only difference is that you need to use the \n character instead of line breaks:

<%= name %>@<%= version %>\nBuild date: <%= buildTime %>\nComments: <%= comments %>

If you don't define a template altogether, it will default to:

<%= name %>@<%= version %>
Build date: <%= buildDate %>

Running the Example

Clone this repo, move to the example folder and download the dependencies:

cd example
npm install

To check how the plugin behaves with Webpack Dev Server, run:

npm start

To trigger the plugin when building the bundle with Webpack, run:

npm run build

Credits

This plugin was inspired by morficus/version-file.

License

MIT

webpack-version-file's People

Contributors

dependabot[bot] avatar fed avatar larstollefsen avatar ngehlert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

webpack-version-file's Issues

Avoid generating version file when ran with webpack-dev-server

Right now the version file gets written to disk even when running webpack-dev-server. That shouldn't be the case.

This seems to work just fine with Webpack 1 (seen here):

/**
 * When 'webpack' program is used, constructor name is equal to 'NodeOutputFileSystem'.
 * When 'webpack-dev-server' program is used, constructor name is equal to 'MemoryFileSystem'.
 */
const isMemoryFileSystem = (outputFileSystem: Object): boolean => {
  return outputFileSystem.constructor.name === 'MemoryFileSystem';
};

if (!isMemoryFileSystem(compiler.outputFileSystem) && !options.force) {
  return false;
}

Basically the plugin's apply method receives compiler as its first argument. In the function above:

outputFileSystem = compiler.outputFileSystem.constructor.name;

However it seems compiler.outputFileSystem.constructor.name is always NodeOutputFileSystem for Webpack 2.

More info on the compiler object on the official docs.

Could also use process.argv[1] to get the path to the file being executed, but this won't work if Webpack Dev Server gets executed from the CLI. Should try to use a combination of the two:

const isDevServer = process.argv[1].indexOf('webpack-dev-server') > -1 || someOtherCondition;

Error when using templateString without variable

When specifying a template string without a variable an error is thrown

configuration:

const version = '1.2.3';
new VersionFile({
     output: './version',
     templateString: `${version}`,
     verbose: true,
 }),
TypeError: Cannot read property 'map' of null
    at VersionFile.apply (~myDir/node_modules/webpack-version-file/lib/index.js:82:73)

I already create a pull request #6

Error: You are using the following variables which haven't been populated: buildDate...

Seems that v0.1.4 introduced changes where the context of buildDate in the template is no longer accessible.

Up to v0.1.3, this config worked:

config.plugins.push(
    new VersionFile({
        output: path.resolve(paths.old_web_proj, 'ViewModels/Version', 'AppVersionCurrent.cs'),
        templateString: '//generated by __filename webpack.prod.config.js\n' +
                        'namespace StrangeBrew.Web.ViewModels.Version\n' +
                        '{\n' +
                        '    public partial class AppVersion\n' +
                        '    {\n' +
                        '        public static readonly AppVersion Current = new AppVersion(\n' +
                        '                name: "<%= name %>",\n' +
                        '                version: "<%= version %>",\n' +
                        '                year: <%= buildDate.getYear()+1900 %>,\n' +
                        '                month: <%= buildDate.getMonth()+1 %>,\n' +
                        '                day: <%= buildDate.getDate() %>,\n' +
                        '                hour: <%= buildDate.getHours() %>,\n' +
                        '                minute: <%= buildDate.getMinutes() %>,\n' +
                        '                gmtOffsetMinutes: <%= buildDate.getTimezoneOffset() %>);\n' +
                        '    }\n' +
                        '}'
    }),
    new VersionFile({
        output:  path.resolve(paths.src, 'data/stores/', 'version.ts'),
        templateString: "import {IAppVersion} from './IAppVersion';\n\n" +
        "export const BrewNinjaAppVersion: IAppVersion = { \n" +
        "    Name: '<%= name %>', \n" +
        "    Version: '<%= version %>', \n" +
        "    Date: '<%= buildDate %>' \n" +
        "};"
    }),

    new webpack.DefinePlugin({
        "process.env": {
            NODE_ENV: JSON.stringify("production"),
        }
    })
);

v0.1.4 generates the above error, with no other code changes other than updated version. Stacktrace:

 at VersionFile.apply (C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\webpack-version-file\lib\index.js:97:15)
    at webpack (C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\webpack\lib\webpack.js:51:13)
    at processOptions (C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\webpack-cli\bin\cli.js:272:16)
    at yargs.parse (C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\webpack-cli\bin\cli.js:364:3)
    at Object.parse (C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\yargs\yargs.js:567:18)
    at C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\webpack-cli\bin\cli.js:49:8
    at Object.<anonymous> (C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\webpack-cli\bin\cli.js:366:3)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (C:\Users\jperi\Developer\BrewNinja\StrangeBrewWeb\StrangeBrew.App\node_modules\webpack\bin\webpack.js:156:2)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Recommend re-tagging as v0.2.0 so that ^0.1.3 references in package.json don't inadvertently update to v0.1.4.

Access properties in Javascript

Hey!

Thank you for this great plugin!

I am using it with Angular, and I was wondering of there is a way of accessing this variables that you use on the templates directly on the javascript, so the app can show the build version the browser is running.

If I fetch the end file generated, there are some chances of the bundle file being outdated, but fetching a more recent version code.

Gabriel

Emit version file in `watch` mode

My usecase is to provide the functionality of watching build version to give an ability to manually reload the page to load new build. I'm using watch mode for development and in this mode plugin doesn't emit new file on each new incremental build. It would be great to have such a great function.

Benefits of writing file to disk after webpack finished running?

Shall we write the file to disk only after Webpack finished bundling our code? We could make use the compiler done callback as noted here on the official docs.

function HelloWorldPlugin(options) {
  // Setup the plugin instance with options...
}

HelloWorldPlugin.prototype.apply = function(compiler) {
  compiler.plugin('done', function() {
    console.log('Hello World!'); 
  });
};

module.exports = HelloWorldPlugin;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.