Merge pull request #7 from radswiat/feature/improvements

Feature/improvements
This commit is contained in:
Radek 2017-04-11 00:17:16 +01:00 committed by GitHub
commit 349ef89671
42 changed files with 1732 additions and 4654 deletions

18
.babelrc Normal file
View file

@ -0,0 +1,18 @@
{
"babelrc": false,
"presets": [
"es2015",
"stage-2"
],
"plugins": [
["module-resolver", {
"root": ["./src/"],
"alias": {
"config": "./config",
"core": "./core",
"components": "./components"
}
}],
"transform-runtime"
]
}

5
.gitignore vendored
View file

@ -1,3 +1,4 @@
.idea .idea/
node_modules node_modules/
demo/node_modules/
npm-debug* npm-debug*

View file

@ -1,2 +1,2 @@
npm-debug* npm-debug*
.idea .idea/

View file

@ -1,16 +1,24 @@
# Auto inject version - Webpack plugin # Auto inject version - Webpack plugin
## Add version to bundle automatically Adds version from package.json into every single file as top comment block.
## What ### Install
```console
$ npm install webpack-auto-inject-version --save-dev
```
# What it gives you
Auto Inject Version (AIV) can: Auto Inject Version (AIV) can:
- inject version from package.json into every bundle file as a comment ( at the top ) - inject version from package.json into every bundle file as a comment ( at the top )
- inject version from package.json into any place in your HTML by special tag <{version}> - inject version from package.json into any place in your HTML by special tag `[AIV]{version}[/AIV]`
- inject version from package.json into any place in CSS/JS file by special tag <{version}> - inject version from package.json into any place in CSS/JS file by special tag `[AIV]{version}[/AIV]`
- auto increase version by --major, --minor, --patch and then inject as chosen - auto increase package.json version by --env.major, --env.minor, --env.patch passed into webpack
## Desc ## Example
Please take a look into `demo/` folder.
## Inject example
AIV can inject version number for all your bundle files (css,js,html).<br><br> AIV can inject version number for all your bundle files (css,js,html).<br><br>
Example js:
```js ```js
// [AIV] Build version: 1.0.10 // [AIV] Build version: 1.0.10
/******/ (function(modules) { // webpackBootstrap /******/ (function(modules) { // webpackBootstrap
@ -25,29 +33,21 @@ Example html:
<html lang="en"> <html lang="en">
``` ```
AIV can also auto inject your version number into html by using special code ( <{version}> ).<br><br>
Example:
```html
<span>My awesome project | <{version}></span>
```
<br>
## Install
```console
$ npm install webpack-auto-inject-version --save-dev
```
<br>
## Usage
# How to configure
In webpack.conf.js ( or any name of webpack conf file )
```js ```js
var WebpackAutoInject = require('webpack-auto-inject-version'); var WebpackAutoInject = require('webpack-auto-inject-version');
module.exports = { module.exports = {
plugins: [ plugins: [
new WebpackAutoInject(options) new WebpackAutoInject({
// options
// example:
components: {
AutoIncreaseVersion: false
}
})
] ]
} }
``` ```
@ -56,11 +56,11 @@ module.exports = {
## Options ## Options
### autoIncrease ### components.AutoIncreaseVersion
Auto increase package.json number. <br> Auto increase package.json number. <br>
This option requires extra argument to be sent to webpack build. <br> This option requires extra argument to be sent to webpack build. <br>
It happens before anything else to make sure that your new version is injected into your files.<br> It happens before anything else to make sure that your new version is injected into your files.<br>
Arguments: --major --minor --patch<br><br> Arguments: --env.major --env.minor --env.patch<br><br>
<br> <br>
@ -68,39 +68,38 @@ Example for package.json run type, npm run start => ( 1.2.10 to 2.0.0 )
```json ```json
"version" : "1.2.10", "version" : "1.2.10",
"scripts": { "scripts": {
"start": "webpack --major" "start": "webpack --env.major"
} }
``` ```
Default: true Default: true
<br> <br>
### injectByTag ### components.InjectByTag
Inject version number into your file<br> Inject version number into your file<br>
Version will replace the <{version}> tag.<br> Version will replace the <{version}> tag.<br>
```html ```html
<span>My awesome project | <{version}></span> <span>My awesome project | [AIV]{version}[/AIV]</span>
``` ```
```js ```js
var version = '<{version}>'; var version = '[AIV]{version}[/AIV]';
``` ```
Default: true Default: true
<br> <br>
### components.InjectAsComment
### injectByTagFileRegex
Regex against file name. If match, injectByTag will try to find version tag and replace it.
Only html files: /^(.){1,}\.html$/ <br>
Only js files: ^(.){1,}\.js$ <br>
Any file: (.){1,} <br>
Default: /^index\.html$/
<br>
### injectAsComment
This will inject your version as a comment into any css,js,html file.<br> This will inject your version as a comment into any css,js,html file.<br>
Default: true Default: true
# Development advice
Demo has been created to simplify the testing of the webpack-plugin,
if you would like to work on this webpack plugin you should:
* clone the repo
* npm install on ./ & ./demo
* npm start on ./
* and then you can test your code by demo/ npm start

94
demo/dist/index-bundle.js vendored Normal file
View file

@ -0,0 +1,94 @@
// [AIV] Build version: 0.5.1
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = "<!DOCTYPE html><html lang=en><head><meta charset=UTF-8><title>Title</title></head><body><span>My awesome project | 0.5.1></span></body></html>"
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
var html = __webpack_require__(0);
/**
* Sample code
* @type {number}
*/
var myVariable = 5;
var test = function(val) {
return val * val;
};
test(myVariable);
/***/ })
/******/ ]);

18
demo/package.json Normal file
View file

@ -0,0 +1,18 @@
{
"name": "example-using-inject",
"version": "0.13.4",
"description": "This is an example how to use webpack-auto-inject-version plugin in webpack",
"scripts": {
"start": "webpack --config ./webpack.conf.js",
"patch": "webpack --config ./webpack.conf.js --env.patch",
"minor": "webpack --config ./webpack.conf.js --env.minor",
"major": "webpack --config ./webpack.conf.js --env.major"
},
"author": "Radoslaw Swiat",
"license": "ISC",
"devDependencies": {
"html-minify-loader": "^1.1.0",
"raw-loader": "^0.5.1",
"webpack": "^2.3.3"
}
}

10
demo/src/index.html Normal file
View file

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>My awesome project | [AIV]{version}[/AIV]></span>
</body>
</html>

3
demo/src/main.css Normal file
View file

@ -0,0 +1,3 @@
body {
backgroun: red;
}

11
demo/src/main.js Normal file
View file

@ -0,0 +1,11 @@
var html = require('./index.html');
/**
* Sample code
* @type {number}
*/
var myVariable = 5;
var test = function(val) {
return val * val;
};
test(myVariable);

50
demo/webpack.conf.js Normal file
View file

@ -0,0 +1,50 @@
var path = require('path');
// Require WebpackAutoInject from npm installed modules ( preferred )
// var WebpackAutoInject = require('webpack-auto-inject-version').default;
// Require WebpackAutoInject from dist - dev purpose only ( do not use the below line )
var WebpackAutoInject = require('../dist/WebpackAutoInjectVersion').default;
module.exports = {
entry: {
index: './src/main.js'
},
resolve: {
extensions: ['.js', '.html']
},
output: {
filename: '[name]-bundle.js',
path: path.resolve(process.cwd(), 'dist')
},
module: {
loaders: [
{
test: /\.js$/,
include: [
path.resolve('src')
]
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.txt$/,
loader: 'raw-loader'
},
{
test: /\.html$/,
loader: 'raw-loader!html-minify-loader'
}
]
},
plugins: [
new WebpackAutoInject({
PACKAGE_JSON_PATH: '../package.json',
components: {
AutoIncreaseVersion: true,
InjectAsComment: true,
InjectByTag: true
}
})
]
};

977
dist/WebpackAutoInjectVersion.js vendored Normal file
View file

@ -0,0 +1,977 @@
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("babel-runtime/helpers/classCallCheck"), require("babel-runtime/helpers/createClass"), require("chalk"), require("path"), require("babel-runtime/core-js/promise"), require("fs"), require("os"), require("babel-runtime/helpers/asyncToGenerator"), require("babel-runtime/regenerator"), require("lodash"), require("babel-runtime/core-js/json/stringify"), require("optimist"), require("semver"));
else if(typeof define === 'function' && define.amd)
define(["babel-runtime/helpers/classCallCheck", "babel-runtime/helpers/createClass", "chalk", "path", "babel-runtime/core-js/promise", "fs", "os", "babel-runtime/helpers/asyncToGenerator", "babel-runtime/regenerator", "lodash", "babel-runtime/core-js/json/stringify", "optimist", "semver"], factory);
else {
var a = typeof exports === 'object' ? factory(require("babel-runtime/helpers/classCallCheck"), require("babel-runtime/helpers/createClass"), require("chalk"), require("path"), require("babel-runtime/core-js/promise"), require("fs"), require("os"), require("babel-runtime/helpers/asyncToGenerator"), require("babel-runtime/regenerator"), require("lodash"), require("babel-runtime/core-js/json/stringify"), require("optimist"), require("semver")) : factory(root["babel-runtime/helpers/classCallCheck"], root["babel-runtime/helpers/createClass"], root["chalk"], root["path"], root["babel-runtime/core-js/promise"], root["fs"], root["os"], root["babel-runtime/helpers/asyncToGenerator"], root["babel-runtime/regenerator"], root["lodash"], root["babel-runtime/core-js/json/stringify"], root["optimist"], root["semver"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, function(__WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_5__, __WEBPACK_EXTERNAL_MODULE_6__, __WEBPACK_EXTERNAL_MODULE_7__, __WEBPACK_EXTERNAL_MODULE_9__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__, __WEBPACK_EXTERNAL_MODULE_15__, __WEBPACK_EXTERNAL_MODULE_17__, __WEBPACK_EXTERNAL_MODULE_18__, __WEBPACK_EXTERNAL_MODULE_19__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 16);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("babel-runtime/helpers/classCallCheck");
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = require("babel-runtime/helpers/createClass");
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("chalk");
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
PACKAGE_JSON_PATH: './package.json',
components: {
AutoIncreaseVersion: true,
InjectAsComment: true,
InjectByTag: true
},
componentsOptions: {
InjectByTag: {
fileRegex: /\.+/
}
},
LOGS_TEXT: {
AIS_START: 'Auto inject version started'
}
};
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _config = __webpack_require__(3);
var _config2 = _interopRequireDefault(_config);
var _chalk = __webpack_require__(2);
var _chalk2 = _interopRequireDefault(_chalk);
var _utils = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var endOfLine = __webpack_require__(9).EOL;
var Log = function () {
// default 1
function Log() {
(0, _classCallCheck3.default)(this, Log);
this.logLevel = 3;
this.getLogLevel();
}
(0, _createClass3.default)(Log, [{
key: 'getLogLevel',
value: function getLogLevel() {
if ((0, _utils.isArgv)('aiv-log-full')) {
this.logLevel = 3;
} else if ((0, _utils.isArgv)('aiv-log-none')) {
this.logLevel = 0;
}
}
/**
* Get console log head
* @returns {string}
*/
}, {
key: 'getHead',
value: function getHead() {
return endOfLine + _chalk2.default.bgYellow.black('[AIV] : ');
}
/**
* Get log text by ID from config file
*/
}, {
key: 'getText',
value: function getText(id) {
return _config2.default.LOGS_TEXT[id];
}
/**
* Call any type
* @param type
* @param msg
*/
}, {
key: 'call',
value: function call(type, msgId) {
if (typeof this[type] === 'function') {
this[type](this.getText(msgId));
}
}
}, {
key: 'error',
value: function error(msg) {
if (this.logLevel < 3) return;
console.log(this.getHead() + ' ' + _chalk2.default.red('error') + ' : ' + msg);
}
}, {
key: 'info',
value: function info(msg) {
if (!this.logLevel) return;
console.log(this.getHead() + ' ' + _chalk2.default.blue('info') + ' : ' + msg);
}
}, {
key: 'warn',
value: function warn(msg) {
if (!this.logLevel) return;
console.log(this.getHead() + ' ' + _chalk2.default.yellow('warn') + ' : ' + msg);
}
}]);
return Log;
}();
exports.default = new Log();
/***/ }),
/* 5 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = require("babel-runtime/core-js/promise");
/***/ }),
/* 7 */
/***/ (function(module, exports) {
module.exports = require("fs");
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isArgv = isArgv;
exports.merge = merge;
var argv = __webpack_require__(18).argv;
/**
* Get argv from webpack env[argv]
* Since webpack 2.0 we have to pass args by the env
* example:
* - webpack --config ./webpack.conf.js --env.patch
* @param arg
* @returns {boolean}
*/
function isArgv(arg) {
return Boolean(argv.env[arg]);
}
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge(obj1, obj2) {
var obj3 = {};
for (var attrname in obj1) {
obj3[attrname] = obj1[attrname];
}
for (var attrname in obj2) {
obj3[attrname] = obj2[attrname];
}
return obj3;
}
/***/ }),
/* 9 */
/***/ (function(module, exports) {
module.exports = require("os");
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = __webpack_require__(17);
var _stringify2 = _interopRequireDefault(_stringify);
var _promise = __webpack_require__(6);
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _semver = __webpack_require__(19);
var _semver2 = _interopRequireDefault(_semver);
var _config = __webpack_require__(3);
var _config2 = _interopRequireDefault(_config);
var _path = __webpack_require__(5);
var _path2 = _interopRequireDefault(_path);
var _fs = __webpack_require__(7);
var _fs2 = _interopRequireDefault(_fs);
var _utils = __webpack_require__(8);
var _chalk = __webpack_require__(2);
var _chalk2 = _interopRequireDefault(_chalk);
var _log = __webpack_require__(4);
var _log2 = _interopRequireDefault(_log);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var AutoIncreaseVersion = function () {
function AutoIncreaseVersion(context) {
(0, _classCallCheck3.default)(this, AutoIncreaseVersion);
this.context = context;
}
(0, _createClass3.default)(AutoIncreaseVersion, [{
key: 'apply',
value: function apply() {
var _this = this;
return new _promise2.default(function (resolve, reject) {
_this.resolve = resolve;
_this.reject = reject;
_this.start();
});
}
/**
* Start version increase
* - decide scenario: major, minor, patch
*/
}, {
key: 'start',
value: function start() {
this.packageFile = this.openPackageFile();
if ((0, _utils.isArgv)('major')) {
this.major();
} else if ((0, _utils.isArgv)('minor')) {
this.minor();
} else if ((0, _utils.isArgv)('patch')) {
this.patch();
} else {
this.reject();
}
}
/**
* Open package file
* @returns {any}
*/
}, {
key: 'openPackageFile',
value: function openPackageFile() {
return JSON.parse(_fs2.default.readFileSync(_path2.default.resolve(this.context.config.PACKAGE_JSON_PATH), 'utf8'));
}
/**
* Close & save package file
* @param newVersion
*/
}, {
key: 'closePackageFile',
value: function closePackageFile(newVersion) {
var _this2 = this;
this.packageFile.version = newVersion;
_fs2.default.writeFile(_path2.default.resolve(this.context.config.PACKAGE_JSON_PATH), (0, _stringify2.default)(this.packageFile, null, 4), function (err) {
if (err) {
_this2.reject(err);return console.log(err);
}
_log2.default.info('autoIncVersion : new version : ' + newVersion);
_log2.default.info('package.json updated!');
_this2.context.version = newVersion;
_this2.resolve();
});
}
/**
* Increase major
*/
}, {
key: 'major',
value: function major() {
var newVersion = _semver2.default.inc(this.packageFile.version, 'major');
this.closePackageFile(newVersion);
}
/**
* Increase minor
*/
}, {
key: 'minor',
value: function minor() {
var newVersion = _semver2.default.inc(this.packageFile.version, 'minor');
this.closePackageFile(newVersion);
}
/**
* Increase patch
*/
}, {
key: 'patch',
value: function patch() {
var newVersion = _semver2.default.inc(this.packageFile.version, 'patch');
this.closePackageFile(newVersion);
}
}]);
return AutoIncreaseVersion;
}();
AutoIncreaseVersion.componentName = 'AutoIncreaseVersion';
exports.default = AutoIncreaseVersion;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = __webpack_require__(6);
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _chalk = __webpack_require__(2);
var _chalk2 = _interopRequireDefault(_chalk);
var _path = __webpack_require__(5);
var _path2 = _interopRequireDefault(_path);
var _config = __webpack_require__(3);
var _config2 = _interopRequireDefault(_config);
var _log = __webpack_require__(4);
var _log2 = _interopRequireDefault(_log);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var endOfLine = __webpack_require__(9).EOL;
/**
* Inject version number into HTML
* - done by parsing html file,
* > replace: <{version}>
*/
var InjectAsComment = function () {
function InjectAsComment(context) {
(0, _classCallCheck3.default)(this, InjectAsComment);
this.context = context;
}
(0, _createClass3.default)(InjectAsComment, [{
key: 'apply',
value: function apply() {
var _this = this;
this.context.compiler.plugin('emit', function (compilation, cb) {
for (var basename in compilation.assets) {
var ext = _path2.default.extname(basename);
var asset = compilation.assets[basename];
switch (ext) {
case '.js':
_this.injectIntoJs(asset);
break;
case '.html':
_this.injectIntoHtml(asset);
break;
case '.css':
_this.injectIntoCss(asset);
break;
case 'default':
break;
}
_log2.default.info('InjectAsComment : match : ' + basename + ' : injected : ' + _this.context.version);
}
cb();
});
return new _promise2.default(function (resolve, reject) {
resolve();
});
}
}, {
key: 'injectIntoCss',
value: function injectIntoCss(asset) {
var modAsset = '/** [' + _config2.default.SHORT + '] Build version: ' + this.context.version + ' **/ ' + endOfLine + ' ' + asset.source() + ' ';
asset.source = function () {
return modAsset;
};
}
}, {
key: 'injectIntoHtml',
value: function injectIntoHtml(asset) {
var modAsset = '<!-- [' + _config2.default.SHORT + '] Build version: ' + this.context.version + ' --> ' + endOfLine + ' ' + asset.source() + ' ';
asset.source = function () {
return modAsset;
};
}
}, {
key: 'injectIntoJs',
value: function injectIntoJs(asset) {
var modAsset = '// [' + _config2.default.SHORT + '] Build version: ' + this.context.version + ' ' + endOfLine + ' ' + asset.source() + ' ';
asset.source = function () {
return modAsset;
};
}
}]);
return InjectAsComment;
}();
InjectAsComment.componentName = 'InjectAsComment';
exports.default = InjectAsComment;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = __webpack_require__(6);
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _log = __webpack_require__(4);
var _log2 = _interopRequireDefault(_log);
var _chalk = __webpack_require__(2);
var _chalk2 = _interopRequireDefault(_chalk);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Inject version number into HTML
* - done by parsing html file,
* > replace: <{version}>
*/
var InjectByTag = function () {
function InjectByTag(context) {
(0, _classCallCheck3.default)(this, InjectByTag);
this.context = context;
}
(0, _createClass3.default)(InjectByTag, [{
key: 'apply',
value: function apply() {
var _this = this;
this.context.compiler.plugin('emit', function (compilation, cb) {
// for every output file
for (var basename in compilation.assets) {
// only if match regex
if (_this.context.config.componentsOptions.InjectByTag.fileRegex.test(basename)) {
(function () {
var replaced = 0;
var asset = compilation.assets[basename];
var modFile = asset.source().replace(/(\[AIV\]{version}\[\/AIV\])/g, function () {
replaced++;
return _this.context.version;
});
asset.source = function () {
return modFile;
};
_log2.default.info('InjectByTag : match : ' + basename + ' : replaced : ' + replaced);
})();
}
}
cb();
});
return new _promise2.default(function (resolve, reject) {
resolve();
});
}
}]);
return InjectByTag;
}();
InjectByTag.componentName = 'InjectByTag';
exports.default = InjectByTag;
/***/ }),
/* 13 */
/***/ (function(module, exports) {
module.exports = require("babel-runtime/helpers/asyncToGenerator");
/***/ }),
/* 14 */
/***/ (function(module, exports) {
module.exports = require("babel-runtime/regenerator");
/***/ }),
/* 15 */
/***/ (function(module, exports) {
module.exports = require("lodash");
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = __webpack_require__(14);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(13);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _chalk = __webpack_require__(2);
var _chalk2 = _interopRequireDefault(_chalk);
var _fs = __webpack_require__(7);
var _fs2 = _interopRequireDefault(_fs);
var _path = __webpack_require__(5);
var _path2 = _interopRequireDefault(_path);
var _config = __webpack_require__(3);
var _config2 = _interopRequireDefault(_config);
var _log = __webpack_require__(4);
var _log2 = _interopRequireDefault(_log);
var _lodash = __webpack_require__(15);
var _autoIncreaseVersion = __webpack_require__(10);
var _autoIncreaseVersion2 = _interopRequireDefault(_autoIncreaseVersion);
var _injectAsComment = __webpack_require__(11);
var _injectAsComment2 = _interopRequireDefault(_injectAsComment);
var _injectByTag = __webpack_require__(12);
var _injectByTag2 = _interopRequireDefault(_injectByTag);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var WebpackAutoInject = function () {
/**
* Constructor,
* called on webpack config load
* @param userConfig - config from the webpack config file
*/
function WebpackAutoInject(userConfig) {
(0, _classCallCheck3.default)(this, WebpackAutoInject);
this.setConfig(userConfig);
var packageFile = JSON.parse(_fs2.default.readFileSync(_path2.default.resolve(this.config.PACKAGE_JSON_PATH), 'utf8'));
this.version = packageFile.version;
_log2.default.call('info', 'AIS_START');
this.executeNoneWebpackComponents();
}
(0, _createClass3.default)(WebpackAutoInject, [{
key: 'setConfig',
value: function setConfig(userConfig) {
this.config = (0, _lodash.merge)(_config2.default, userConfig);
// lets convert all components names to lowercase - to prevent issues
this.config.components = (0, _lodash.transform)(this.config.components, function (result, val, key) {
result[key.toLowerCase()] = val;
});
this.config = (0, _lodash.merge)(this.config, WebpackAutoInject.protectedConfig);
}
/**
* Webpack apply call,
* when webpack is initialized and
* plugin has been called by webpack
* @param compiler
*/
}, {
key: 'apply',
value: function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(compiler) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this.compiler = compiler;
_context.next = 3;
return this.executeWebpackComponents();
case 3:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function apply(_x) {
return _ref.apply(this, arguments);
}
return apply;
}()
/**
* Execute none webpack components
* - runs as soon as possible,
* > without waiting for webpack init
*/
}, {
key: 'executeNoneWebpackComponents',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2() {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.executeComponent([_autoIncreaseVersion2.default]);
case 2:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function executeNoneWebpackComponents() {
return _ref2.apply(this, arguments);
}
return executeNoneWebpackComponents;
}()
/**
* Execute webpack components
* - runs when webpack is initialized
* and plugins is called by webpack
*/
}, {
key: 'executeWebpackComponents',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.executeComponent([_injectAsComment2.default, _injectByTag2.default]);
case 2:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function executeWebpackComponents() {
return _ref3.apply(this, arguments);
}
return executeWebpackComponents;
}()
/**
* Execute components,
* - general layer for comp execution
* - used for both, webpack and non webpack comp
*/
}, {
key: 'executeComponent',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4(components) {
var ComponentClass, inst;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (components.length) {
_context4.next = 2;
break;
}
return _context4.abrupt('return');
case 2:
// take first component class
ComponentClass = components.shift();
// if component is disabled, call next component
if (this.config.components[ComponentClass.componentName.toLowerCase()]) {
_context4.next = 7;
break;
}
_context4.next = 6;
return this.executeComponent(components);
case 6:
return _context4.abrupt('return');
case 7:
// execute component
inst = new ComponentClass(this);
// await for apply to finish
_context4.next = 10;
return inst.apply();
case 10:
_context4.next = 12;
return this.executeComponent(components);
case 12:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function executeComponent(_x2) {
return _ref4.apply(this, arguments);
}
return executeComponent;
}()
}]);
return WebpackAutoInject;
}();
// import sub components
WebpackAutoInject.protectedConfig = {
NAME: 'Auto Inject Version',
SHORT: 'AIV'
};
exports.default = WebpackAutoInject;
/***/ }),
/* 17 */
/***/ (function(module, exports) {
module.exports = require("babel-runtime/core-js/json/stringify");
/***/ }),
/* 18 */
/***/ (function(module, exports) {
module.exports = require("optimist");
/***/ }),
/* 19 */
/***/ (function(module, exports) {
module.exports = require("semver");
/***/ })
/******/ ]);
});

View file

@ -1,67 +0,0 @@
var semver = require('semver');
var config = require('../config');
var path = require('path');
var fs = require('fs');
var u = require('../core/utils');
var chalk = require('chalk');
var Promise = require('bluebird');
var log = require('../core/log');
var IncVersion = (function () {
function IncVersion(context) {
this.context = context;
}
IncVersion.prototype.apply = function () {
var _this = this;
return new Promise(function (resolve, reject) {
_this.resolve = resolve;
_this.reject = reject;
_this.start();
});
};
IncVersion.prototype.start = function () {
this.packageFile = this.openPackageFile();
if (u.isArgv('major')) {
this.major();
}
else if (u.isArgv('minor')) {
this.minor();
}
else if (u.isArgv('patch')) {
this.patch();
}
else {
this.reject();
}
};
IncVersion.prototype.openPackageFile = function () {
return JSON.parse(fs.readFileSync(path.normalize(config.PATH_PACKAGE), 'utf8'));
};
IncVersion.prototype.closePackageFile = function (newVersion) {
var _this = this;
this.packageFile.version = newVersion;
fs.writeFile(path.normalize(config.PATH_PACKAGE), JSON.stringify(this.packageFile, null, 4), function (err) {
if (err) {
_this.reject(err);
return console.log(err);
}
log.info("autoIncVersion : new version : " + newVersion);
log.info('package.json updated!');
_this.context.version = newVersion;
_this.resolve();
});
};
IncVersion.prototype.major = function () {
var newVersion = semver.inc(this.packageFile.version, 'major');
this.closePackageFile(newVersion);
};
IncVersion.prototype.minor = function () {
var newVersion = semver.inc(this.packageFile.version, 'minor');
this.closePackageFile(newVersion);
};
IncVersion.prototype.patch = function () {
var newVersion = semver.inc(this.packageFile.version, 'patch');
this.closePackageFile(newVersion);
};
return IncVersion;
}());
module.exports = IncVersion;

View file

@ -1,49 +0,0 @@
var chalk = require('chalk');
var path = require('path');
var endOfLine = require('os').EOL;
var config = require('../config');
var log = require('../core/log');
'use strict';
var InjectAsComment = (function () {
function InjectAsComment(context) {
this.context = context;
}
InjectAsComment.prototype.apply = function () {
var _this = this;
this.context.compiler.plugin('emit', function (compilation, cb) {
for (var basename in compilation.assets) {
var ext = path.extname(basename);
var asset = compilation.assets[basename];
switch (ext) {
case '.js':
_this.injectIntoJs(asset);
break;
case '.html':
_this.injectIntoHtml(asset);
break;
case '.css':
_this.injectIntoCss(asset);
break;
case 'default': break;
}
log.info("InjectAsComment : match : " + basename + " : injected : " + _this.context.version);
}
cb();
});
return new Promise(function (resolve, reject) { resolve(); });
};
InjectAsComment.prototype.injectIntoCss = function (asset) {
var modAsset = "/** [" + config.SHORT + "] Build version: " + this.context.version + " **/" + endOfLine + asset.source();
asset.source = function () { return modAsset; };
};
InjectAsComment.prototype.injectIntoHtml = function (asset) {
var modAsset = "<!-- [" + config.SHORT + "] Build version: " + this.context.version + " -->" + endOfLine + asset.source();
asset.source = function () { return modAsset; };
};
InjectAsComment.prototype.injectIntoJs = function (asset) {
var modAsset = "// [" + config.SHORT + "] Build version: " + this.context.version + endOfLine + " " + asset.source();
asset.source = function () { return modAsset; };
};
return InjectAsComment;
}());
module.exports = InjectAsComment;

View file

@ -1,31 +0,0 @@
var log = require('../core/log');
'use strict';
var InjectByTag = (function () {
function InjectByTag(context) {
this.context = context;
}
InjectByTag.prototype.apply = function () {
var _this = this;
this.context.compiler.plugin('emit', function (compilation, cb) {
var _loop_1 = function() {
if (_this.context.options.injectByTagFileRegex.test(basename)) {
var replaced_1 = 0;
var asset = compilation.assets[basename];
var modFile_1 = asset.source().replace(/(\<\{version\}\>)/g, function () {
replaced_1++;
return _this.context.version;
});
asset.source = function () { return modFile_1; };
log.info("InjectByTag : match : " + basename + " : replaced : " + replaced_1);
}
};
for (var basename in compilation.assets) {
_loop_1();
}
cb();
});
return new Promise(function (resolve, reject) { resolve(); });
};
return InjectByTag;
}());
module.exports = InjectByTag;

View file

@ -1,46 +0,0 @@
var chalk = require('chalk');
var path = require('path');
var endOfLine = require('os').EOL;
var config = require('./../config');
'use strict';
var InjectIntoAnyFile = (function () {
function InjectIntoAnyFile(context) {
this.context = context;
}
InjectIntoAnyFile.prototype.apply = function () {
var _this = this;
this.context.compiler.plugin('emit', function (compilation, cb) {
for (var basename in compilation.assets) {
var ext = path.extname(basename);
var asset = compilation.assets[basename];
switch (ext) {
case '.js':
_this.injectIntoJs(asset);
break;
case '.html':
_this.injectIntoHtml(asset);
break;
case '.css':
_this.injectIntoCss(asset);
break;
}
}
cb();
});
return new Promise(function (resolve, reject) { resolve(); });
};
InjectIntoAnyFile.prototype.injectIntoCss = function (asset) {
var modAsset = "/** [" + config.SHORT + "] Build version: " + this.context.version + " **/ " + endOfLine + " " + asset.source() + " ";
asset.source = function () { return modAsset; };
};
InjectIntoAnyFile.prototype.injectIntoHtml = function (asset) {
var modAsset = "<!-- [" + config.SHORT + "] Build version: " + this.context.version + " --> " + endOfLine + " " + asset.source() + " ";
asset.source = function () { return modAsset; };
};
InjectIntoAnyFile.prototype.injectIntoJs = function (asset) {
var modAsset = "// [" + config.SHORT + "] Build version: " + this.context.version + " " + endOfLine + " " + asset.source() + " ";
asset.source = function () { return modAsset; };
};
return InjectIntoAnyFile;
}());
module.exports = InjectIntoAnyFile;

View file

@ -1,25 +0,0 @@
'use strict';
var InjectIntoHtml = (function () {
function InjectIntoHtml(context) {
this.context = context;
}
InjectIntoHtml.prototype.apply = function () {
var _this = this;
this.context.compiler.plugin('emit', function (compilation, cb) {
var _loop_1 = function() {
if (_this.context.options.injectIntoHtmlRegex.test(basename)) {
var asset = compilation.assets[basename];
var modFile_1 = asset.source().replace(/(\<\{version\}\>)/g, _this.context.version);
asset.source = function () { return modFile_1; };
}
};
for (var basename in compilation.assets) {
_loop_1();
}
cb();
});
return new Promise(function (resolve, reject) { resolve(); });
};
return InjectIntoHtml;
}());
module.exports = InjectIntoHtml;

24
dist/config.js vendored
View file

@ -1,24 +0,0 @@
module.exports = {
NAME: 'Auto Inject Version',
SHORT: 'AIV',
PATH_PACKAGE: './package.json',
NON_WEBPACK_COMPONENTS: [
{
option: 'autoIncrease',
path: './components/auto-inc-version'
}
],
WEBPACK_COMPONENTS: [
{
option: 'injectByTag',
path: './components/inject-by-tag'
},
{
option: 'injectAsComment',
path: './components/inject-as-comment'
}
],
LOGS_TEXT: {
AIS_START: 'Auto inject version started'
}
};

47
dist/core/log.js vendored
View file

@ -1,47 +0,0 @@
var config = require('../config');
var chalk = require('chalk');
var endOfLine = require('os').EOL;
var u = require('./utils');
var Log = (function () {
function Log() {
this.logLevel = 3;
this.getLogLevel();
}
Log.prototype.getLogLevel = function () {
if (u.isArgv('aiv-log-full')) {
this.logLevel = 3;
}
else if (u.isArgv('aiv-log-none')) {
this.logLevel = 0;
}
};
Log.prototype.getHead = function () {
return endOfLine + chalk.bgYellow.black('[AIV] : ');
};
Log.prototype.getText = function (id) {
return config.LOGS_TEXT[id];
};
Log.prototype.call = function (type, msgId) {
if (typeof this[type] === 'function') {
this[type](this.getText(msgId));
}
};
Log.prototype.error = function (msg) {
if (this.logLevel < 3)
return;
console.log(this.getHead() + " " + chalk.red('error') + " : " + msg);
};
Log.prototype.info = function (msg) {
if (!this.logLevel)
return;
console.log(this.getHead() + " " + chalk.blue('info') + " : " + msg);
};
Log.prototype.warn = function (msg) {
if (!this.logLevel)
return;
console.log(this.getHead() + " " + chalk.yellow('warn') + " : " + msg);
};
return Log;
}());
var log = new Log();
module.exports = log;

21
dist/core/utils.js vendored
View file

@ -1,21 +0,0 @@
var Utils = (function () {
function Utils() {
}
Utils.isArgv = function (arg) {
return Boolean(process.argv.find(function (item) {
return item.substr(0, 2) === '--' && item.indexOf(arg) > -1;
}));
};
Utils.merge = function (obj1, obj2) {
var obj3 = {};
for (var attrname in obj1) {
obj3[attrname] = obj1[attrname];
}
for (var attrname in obj2) {
obj3[attrname] = obj2[attrname];
}
return obj3;
};
return Utils;
}());
module.exports = Utils;

53
dist/main.js vendored
View file

@ -1,53 +0,0 @@
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var config = require('./config');
var Promise = require('bluebird');
var u = require('./core/utils');
var log = require('./core/log');
'use strict';
var WebpackAutoInject = (function () {
function WebpackAutoInject(options) {
this.options = u.merge(WebpackAutoInject.options, options);
var packageFile = JSON.parse(fs.readFileSync(path.normalize(config.PATH_PACKAGE), 'utf8'));
this.version = packageFile.version;
log.call('info', 'AIS_START');
this.executeNoneWebpackComponents();
}
WebpackAutoInject.prototype.apply = function (compiler) {
this.compiler = compiler;
this.executeWebpackComponents();
};
WebpackAutoInject.prototype.executeNoneWebpackComponents = function () {
this.executeComponents(config.NON_WEBPACK_COMPONENTS, function () {
});
};
WebpackAutoInject.prototype.executeWebpackComponents = function () {
this.executeComponents(config.WEBPACK_COMPONENTS, function () {
});
};
WebpackAutoInject.prototype.executeComponents = function (components, done) {
var _this = this;
if (!components.length) {
done();
return;
}
var comp = components.shift();
if (!this.options[comp.option]) {
this.executeComponents(components, done);
return;
}
var inst = new (require(comp.path))(this);
inst.apply().then(function () {
_this.executeComponents(components, done);
}, function (err) { _this.executeComponents(components, done); });
};
WebpackAutoInject.options = {
autoIncrease: true,
injectAsComment: true,
injectByTag: true,
injectByTagFileRegex: /^index\.html$/
};
return WebpackAutoInject;
}());
module.exports = WebpackAutoInject;

View file

@ -1,20 +1,39 @@
{ {
"name": "webpack-auto-inject-version", "name": "webpack-auto-inject-version",
"version": "0.2.0", "version": "0.5.1",
"repository": "radswiat/webpack-auto-inject-version", "repository": "radswiat/webpack-auto-inject-version",
"description": "Webpack plugin for auto inject version from package.json", "description": "Webpack plugin for auto inject version from package.json",
"main": "dist/main.js", "main": "dist/WebpackAutoInjectVersion.js",
"scripts": { "scripts": {
"build": "tsc -w" "start": "babel-node tools/compile.js"
}, },
"author": "Radoslaw Swiat", "author": "Radoslaw Swiat",
"license": "ISC", "license": "ISC",
"devDependencies": { "devDependencies": {
"typings": "^1.4.0" "babel-cli": "^6.10.1",
"babel-core": "^6.24.1",
"babel-eslint": "^6.0.0",
"babel-loader": "^6.2.4",
"babel-plugin-module-resolver": "^2.4.0",
"babel-plugin-transform-runtime": "^6.12.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-node5": "^11.0.1",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-2": "^6.22.0",
"eslint": "^2.7.0",
"eslint-config-airbnb": "^6.2.0",
"eslint-loader": "^1.5.0",
"eslint-plugin-babel": "^3.2.0",
"gutil": "^1.6.4",
"webpack": "^2.3.3",
"webpack-node-externals": "^1.5.4"
}, },
"dependencies": { "dependencies": {
"bluebird": "^3.4.6", "bluebird": "^3.4.6",
"semver": "^5.3.0", "chalk": "^1.1.3",
"chalk": "^1.1.3" "lodash": "^4.17.4",
"minimist": "^1.2.0",
"optimist": "^0.6.1",
"semver": "^5.3.0"
} }
} }

View file

@ -1,92 +0,0 @@
const semver = require('semver');
const config = require('../config');
const path = require('path');
const fs = require('fs');
const u = require('../core/utils');
const chalk = require('chalk');
const Promise = require('bluebird');
const log = require('../core/log');
class IncVersion{
private packageFile;
private resolve;
private reject;
constructor(private context) {}
public apply() {
return new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
this.start();
});
}
/**
* Start version increase
* - decide scenario: major, minor, patch
*/
private start() {
this.packageFile = this.openPackageFile();
if( u.isArgv('major') ) {
this.major();
}
else if( u.isArgv('minor') ) {
this.minor();
}else if( u.isArgv('patch') ) {
this.patch();
}else {
this.reject();
}
}
/**
* Open package file
* @returns {any}
*/
private openPackageFile() {
return JSON.parse(fs.readFileSync(path.normalize(config.PATH_PACKAGE), 'utf8'));
}
/**
* Close & save package file
* @param newVersion
*/
private closePackageFile(newVersion) {
this.packageFile.version = newVersion;
fs.writeFile(path.normalize(config.PATH_PACKAGE), JSON.stringify(this.packageFile, null, 4), (err) => {
if(err) {this.reject(err); return console.log(err);}
log.info(`autoIncVersion : new version : ${newVersion}`)
log.info('package.json updated!');
this.context.version = newVersion;
this.resolve();
});
}
/**
* Increase major
*/
private major() {
let newVersion = semver.inc(this.packageFile.version, 'major');
this.closePackageFile(newVersion);
}
/**
* Increase minor
*/
private minor() {
let newVersion = semver.inc(this.packageFile.version, 'minor');
this.closePackageFile(newVersion);
}
/**
* Increase patch
*/
private patch() {
let newVersion = semver.inc(this.packageFile.version, 'patch');
this.closePackageFile(newVersion);
}
}
module.exports = IncVersion;

View file

@ -0,0 +1,92 @@
import semver from 'semver';
import config from 'config';
import path from 'path';
import fs from 'fs';
import { isArgv } from 'core/utils';
import chalk from 'chalk';
import log from 'core/log';
export default class AutoIncreaseVersion{
static componentName = 'AutoIncreaseVersion';
constructor(context) {
this.context = context;
}
apply() {
return new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
this.start();
});
}
/**
* Start version increase
* - decide scenario: major, minor, patch
*/
start() {
this.packageFile = this.openPackageFile();
if( isArgv('major') ) {
this.major();
}
else if( isArgv('minor') ) {
this.minor();
}else if( isArgv('patch') ) {
this.patch();
}else {
this.reject();
}
}
/**
* Open package file
* @returns {any}
*/
openPackageFile() {
return JSON.parse(fs.readFileSync(path.resolve(this.context.config.PACKAGE_JSON_PATH), 'utf8'));
}
/**
* Close & save package file
* @param newVersion
*/
closePackageFile(newVersion) {
this.packageFile.version = newVersion;
fs.writeFile(
path.resolve(this.context.config.PACKAGE_JSON_PATH),
JSON.stringify(this.packageFile, null, 4
), (err) => {
if(err) {this.reject(err); return console.log(err);}
log.info(`autoIncVersion : new version : ${newVersion}`);
log.info('package.json updated!');
this.context.version = newVersion;
this.resolve();
});
}
/**
* Increase major
*/
major() {
let newVersion = semver.inc(this.packageFile.version, 'major');
this.closePackageFile(newVersion);
}
/**
* Increase minor
*/
minor() {
let newVersion = semver.inc(this.packageFile.version, 'minor');
this.closePackageFile(newVersion);
}
/**
* Increase patch
*/
patch() {
let newVersion = semver.inc(this.packageFile.version, 'patch');
this.closePackageFile(newVersion);
}
}

View file

@ -0,0 +1,59 @@
import chalk from 'chalk';
import path from 'path';
import config from 'config';
import log from 'core/log';
const endOfLine = require('os').EOL;
/**
* Inject version number into HTML
* - done by parsing html file,
* > replace: <{version}>
*/
export default class InjectAsComment{
static componentName = 'InjectAsComment';
constructor(context) {
this.context = context;
}
apply() {
this.context.compiler.plugin('emit', (compilation, cb) => {
for ( var basename in compilation.assets ) {
let ext = path.extname(basename);
let asset = compilation.assets[basename];
switch(ext) {
case '.js' :
this.injectIntoJs(asset);
break;
case '.html' :
this.injectIntoHtml(asset);
break;
case '.css' :
this.injectIntoCss(asset);
break;
case 'default': break;
}
log.info(`InjectAsComment : match : ${basename} : injected : ${this.context.version}`);
}
cb();
});
return new Promise((resolve, reject) => { resolve(); })
}
injectIntoCss(asset) {
let modAsset = `/** [${config.SHORT}] Build version: ${this.context.version} **/ ${endOfLine} ${asset.source()} `;
asset.source = () => modAsset;
}
injectIntoHtml(asset) {
let modAsset = `<!-- [${config.SHORT}] Build version: ${this.context.version} --> ${endOfLine} ${asset.source()} `;
asset.source = () => modAsset;
}
injectIntoJs(asset) {
let modAsset = `// [${config.SHORT}] Build version: ${this.context.version} ${endOfLine} ${asset.source()} `;
asset.source = () => modAsset;
}
}

View file

@ -1,59 +0,0 @@
/// <reference path='../../typings/index.d.ts' />
const chalk = require('chalk');
const path = require('path');
const endOfLine = require('os').EOL;
const config = require('../config');
const log = require('../core/log');
'use strict';
/**
* Inject version number into HTML
* - done by parsing html file,
* > replace: <{version}>
*/
class InjectAsComment{
constructor(private context) {}
apply() {
this.context.compiler.plugin('emit', (compilation, cb) => {
for ( var basename in compilation.assets ) {
let ext = path.extname(basename);
let asset = compilation.assets[basename];
switch(ext) {
case '.js' :
this.injectIntoJs(asset);
break;
case '.html' :
this.injectIntoHtml(asset);
break;
case '.css' :
this.injectIntoCss(asset);
break;
case 'default': break;
}
log.info(`InjectAsComment : match : ${basename} : injected : ${this.context.version}`);
}
cb();
});
return new Promise((resolve, reject) => { resolve(); })
}
injectIntoCss(asset) {
let modAsset = `/** [${config.SHORT}] Build version: ${this.context.version} **/ ${endOfLine} ${asset.source()} `;
asset.source = () => modAsset;
}
injectIntoHtml(asset) {
let modAsset = `<!-- [${config.SHORT}] Build version: ${this.context.version} --> ${endOfLine} ${asset.source()} `;
asset.source = () => modAsset;
}
injectIntoJs(asset) {
let modAsset = `// [${config.SHORT}] Build version: ${this.context.version} ${endOfLine} ${asset.source()} `;
asset.source = () => modAsset;
}
}
module.exports = InjectAsComment;

View file

@ -0,0 +1,36 @@
import log from 'core/log';
import chalk from 'chalk';
/**
* Inject version number into HTML
* - done by parsing html file,
* > replace: <{version}>
*/
export default class InjectByTag{
static componentName = 'InjectByTag';
constructor(context) {
this.context = context;
}
apply() {
this.context.compiler.plugin('emit', (compilation, cb) => {
// for every output file
for ( let basename in compilation.assets ) {
// only if match regex
if(this.context.config.componentsOptions.InjectByTag.fileRegex.test(basename)) {
let replaced = 0;
let asset = compilation.assets[basename];
let modFile = asset.source().replace(/(\[AIV\]{version}\[\/AIV\])/g, () => {
replaced++;
return this.context.version;
});
asset.source = () => modFile;
log.info(`InjectByTag : match : ${basename} : replaced : ${replaced}`);
}
}
cb();
});
return new Promise((resolve, reject) => { resolve(); })
}
}

View file

@ -1,37 +0,0 @@
/// <reference path='../../typings/index.d.ts' />
const log = require('../core/log');
'use strict';
/**
* Inject version number into HTML
* - done by parsing html file,
* > replace: <{version}>
*/
class InjectByTag{
constructor(private context) {}
apply() {
this.context.compiler.plugin('emit', (compilation, cb) => {
// for every output file
for ( var basename in compilation.assets ) {
// only if match regex
if(this.context.options.injectByTagFileRegex.test(basename)) {
let replaced = 0;
let asset = compilation.assets[basename];
let modFile = asset.source().replace(/(\<\{version\}\>)/g, () => {
replaced++;
return this.context.version;
});
asset.source = () => modFile;
log.info(`InjectByTag : match : ${basename} : replaced : ${replaced}`);
}
}
cb();
});
return new Promise((resolve, reject) => { resolve(); })
}
}
module.exports = InjectByTag;

16
src/config.js Normal file
View file

@ -0,0 +1,16 @@
export default {
PACKAGE_JSON_PATH: './package.json',
components: {
AutoIncreaseVersion: true,
InjectAsComment: true,
InjectByTag: true
},
componentsOptions: {
InjectByTag: {
fileRegex: /\.+/
}
},
LOGS_TEXT: {
AIS_START: 'Auto inject version started'
}
};

View file

@ -1,24 +0,0 @@
module.exports = {
NAME : 'Auto Inject Version',
SHORT : 'AIV',
PATH_PACKAGE : './package.json',
NON_WEBPACK_COMPONENTS : [
{
option : 'autoIncrease',
path : './components/auto-inc-version'
}
],
WEBPACK_COMPONENTS : [
{
option : 'injectByTag',
path : './components/inject-by-tag'
},
{
option : 'injectAsComment',
path : './components/inject-as-comment'
}
],
LOGS_TEXT : {
AIS_START : 'Auto inject version started'
}
}

66
src/core/log.js Normal file
View file

@ -0,0 +1,66 @@
import config from 'config';
import chalk from 'chalk';
import { isArgv } from 'core/utils';
const endOfLine = require('os').EOL;
class Log{
logLevel = 3; // default 1
constructor() {
this.getLogLevel();
}
getLogLevel() {
if(isArgv('aiv-log-full')){
this.logLevel = 3;
}else if(isArgv('aiv-log-none')) {
this.logLevel = 0;
}
}
/**
* Get console log head
* @returns {string}
*/
getHead() {
return endOfLine + chalk.bgYellow.black('[AIV] : ')
}
/**
* Get log text by ID from config file
*/
getText(id) {
return config.LOGS_TEXT[id];
}
/**
* Call any type
* @param type
* @param msg
*/
call(type, msgId) {
if(typeof this[type] === 'function') {
this[type](this.getText(msgId));
}
}
error (msg) {
if(this.logLevel < 3) return;
console.log(`${this.getHead()} ${chalk.red('error')} : ${msg}`);
}
info (msg) {
if(!this.logLevel) return;
console.log(`${this.getHead()} ${chalk.blue('info')} : ${msg}`);
}
warn (msg) {
if(!this.logLevel) return;
console.log(`${this.getHead()} ${chalk.yellow('warn')} : ${msg}`);
}
}
export default new Log();

View file

@ -1,67 +0,0 @@
const config = require('../config');
const chalk = require('chalk');
const endOfLine = require('os').EOL;
const u = require('./utils');
class Log{
private logLevel = 3; // default 1
constructor() {
this.getLogLevel();
}
private getLogLevel() {
if(u.isArgv('aiv-log-full')){
this.logLevel = 3;
}else if(u.isArgv('aiv-log-none')) {
this.logLevel = 0;
}
}
/**
* Get console log head
* @returns {string}
*/
private getHead() {
return endOfLine + chalk.bgYellow.black('[AIV] : ')
}
/**
* Get log text by ID from config file
*/
private getText(id) {
return config.LOGS_TEXT[id];
}
/**
* Call any type
* @param type
* @param msg
*/
call(type, msgId) {
if(typeof this[type] === 'function') {
this[type](this.getText(msgId));
}
}
error (msg) {
if(this.logLevel < 3) return;
console.log(`${this.getHead()} ${chalk.red('error')} : ${msg}`);
}
info (msg) {
if(!this.logLevel) return;
console.log(`${this.getHead()} ${chalk.blue('info')} : ${msg}`);
}
warn (msg) {
if(!this.logLevel) return;
console.log(`${this.getHead()} ${chalk.yellow('warn')} : ${msg}`);
}
}
var log = new Log();
module.exports = log;

28
src/core/utils.js Normal file
View file

@ -0,0 +1,28 @@
let argv = require('optimist').argv;
/**
* Get argv from webpack env[argv]
* Since webpack 2.0 we have to pass args by the env
* example:
* - webpack --config ./webpack.conf.js --env.patch
* @param arg
* @returns {boolean}
*/
export function isArgv(arg) {
return Boolean(argv.env[arg]);
}
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
export function merge(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}

View file

@ -1,24 +0,0 @@
class Utils{
static isArgv(arg) {
return Boolean(process.argv.find(function(item) {
return item.substr(0, 2) === '--' && item.indexOf(arg) > -1;
}));
}
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
static merge(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
}
module.exports = Utils;

106
src/main.js Normal file
View file

@ -0,0 +1,106 @@
import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
import config from 'config';
import log from 'core/log';
import { merge, transform } from 'lodash';
// import sub components
import AutoIncreaseVersion from 'components/auto-increase-version';
import InjectAsComment from 'components/inject-as-comment';
import InjectByTag from 'components/inject-by-tag';
export default class WebpackAutoInject{
static protectedConfig = {
NAME: 'Auto Inject Version',
SHORT: 'AIV',
};
/**
* Constructor,
* called on webpack config load
* @param userConfig - config from the webpack config file
*/
constructor(userConfig) {
this.setConfig(userConfig);
let packageFile = JSON.parse(
fs.readFileSync(path.resolve(this.config.PACKAGE_JSON_PATH), 'utf8')
);
this.version = packageFile.version;
log.call('info', 'AIS_START');
this.executeNoneWebpackComponents();
}
setConfig(userConfig) {
this.config = merge(config, userConfig);
// lets convert all components names to lowercase - to prevent issues
this.config.components = transform(this.config.components, function (result, val, key) {
result[key.toLowerCase()] = val;
});
this.config = merge(this.config, WebpackAutoInject.protectedConfig);
}
/**
* Webpack apply call,
* when webpack is initialized and
* plugin has been called by webpack
* @param compiler
*/
async apply(compiler) {
this.compiler = compiler;
await this.executeWebpackComponents();
}
/**
* Execute none webpack components
* - runs as soon as possible,
* > without waiting for webpack init
*/
async executeNoneWebpackComponents() {
await this.executeComponent([AutoIncreaseVersion]);
}
/**
* Execute webpack components
* - runs when webpack is initialized
* and plugins is called by webpack
*/
async executeWebpackComponents() {
await this.executeComponent([InjectAsComment, InjectByTag]);
}
/**
* Execute components,
* - general layer for comp execution
* - used for both, webpack and non webpack comp
*/
async executeComponent(components) {
// no more components,
// finish
if(!components.length) {
return;
}
// take first component class
let ComponentClass = components.shift();
// if component is disabled, call next component
if (!this.config.components[ComponentClass.componentName.toLowerCase()]) {
await this.executeComponent(components);
return;
}
// execute component
let inst = new ComponentClass(this);
// await for apply to finish
await inst.apply();
// call next tick
await this.executeComponent(components);
}
}

View file

@ -1,101 +0,0 @@
/// <reference path='../typings/index.d.ts' />
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const config = require('./config');
const Promise = require('bluebird');
const u = require('./core/utils');
const log = require('./core/log');
'use strict';
class WebpackAutoInject{
private options;
private compiler;
private version;
/**
* Default options
*/
static options = {
autoIncrease : true,
injectAsComment : true,
injectByTag : true,
injectByTagFileRegex : /^index\.html$/
}
/**
* Constructor,
* called on webpack config load
* @param options
*/
constructor(options) {
this.options = u.merge(WebpackAutoInject.options, options);
var packageFile = JSON.parse(fs.readFileSync(path.normalize(config.PATH_PACKAGE), 'utf8'));
this.version = packageFile.version;
log.call('info', 'AIS_START');
this.executeNoneWebpackComponents();
}
/**
* Webpack apply call,
* when webpack is initialized and
* plugin has been called by webpack
* @param compiler
*/
protected apply(compiler) {
this.compiler = compiler;
this.executeWebpackComponents();
}
/**
* Execute none webpack components
* - runs as soon as possible,
* > without waiting for webpack init
*/
private executeNoneWebpackComponents() {
this.executeComponents(config.NON_WEBPACK_COMPONENTS, () => {
});
}
/**
* Execute webpack components
* - runs when webpack is initialized
* and plugins is called by webpack
*/
private executeWebpackComponents() {
this.executeComponents(config.WEBPACK_COMPONENTS, () => {
});
}
/**
* Execute components,
* - general layer for comp execution
* - used for both, webpack and non webpack comp
*/
private executeComponents(components, done) {
// no more components,
// finish
if(!components.length) { done(); return;}
// take first component
let comp = components.shift();
// if component is disabled, call next component
if(!this.options[comp.option]) {
this.executeComponents(components, done);
return;
}
// execute component
let inst = new (require(comp.path))(this);
inst.apply().then(() => {
this.executeComponents(components, done);
}, (err) => {this.executeComponents(components, done);})
}
}
module.exports = WebpackAutoInject;

16
tools/compile.js Normal file
View file

@ -0,0 +1,16 @@
import webpack from 'webpack';
import gutil from 'gutil';
import webpackConfig from './webpack.conf';
function run() {
console.log('compiling');
let compiler = webpack(webpackConfig);
compiler.run((err, stats) => {
gutil.log('[webpack:build]', stats.toString({
chunks: false, // Makes the build much quieter
colors: true
}));
});
}
run();

47
tools/webpack.conf.js Normal file
View file

@ -0,0 +1,47 @@
import path from 'path';
const webpack = require('webpack');
import nodeExternals from 'webpack-node-externals';
export default {
target: 'node',
externals: [nodeExternals()],
entry: './src/main.js',
resolve: {
extensions: ['.js']
},
output: {
filename: 'WebpackAutoInjectVersion.js',
path: path.resolve(process.cwd(), 'dist'),
libraryTarget: 'umd'
},
module: {
// rules: [
// { // eslint feature
// enforce: 'pre',
// test: /\.js$/,
// loader: 'eslint-loader',
// exclude: /node_modules/
// }
// ],
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
include: [
path.resolve('src')
]
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.txt$/,
loader: 'raw-loader'
}
]
},
plugins: [
]
};

View file

@ -1,17 +0,0 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"suppressImplicitAnyIndexErrors": true,
"outDir": "./dist"
},
"filesGlob": [
"./src/"
]
}

View file

@ -1,5 +0,0 @@
{
"globalDependencies": {
"node": "registry:dt/node#6.0.0+20161019125345"
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,8 +0,0 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/988a48ab2cfff3243868d70d836332a118d9f060/node/node.d.ts",
"raw": "registry:dt/node#6.0.0+20161019125345",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/988a48ab2cfff3243868d70d836332a118d9f060/node/node.d.ts"
}
}

1
typings/index.d.ts vendored
View file

@ -1 +0,0 @@
/// <reference path="globals/node/index.d.ts" />