Finilize new version

This commit is contained in:
radswiat 2017-04-11 00:11:09 +01:00
parent 05e79420c4
commit b7e9f047fd
24 changed files with 1537 additions and 831 deletions

View file

@ -9,7 +9,8 @@
"root": ["./src/"], "root": ["./src/"],
"alias": { "alias": {
"config": "./config", "config": "./config",
"core": "./core" "core": "./core",
"components": "./components"
} }
}], }],
"transform-runtime" "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.2.12
/******/ (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.2.12></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);
/***/ })
/******/ ]);

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);

View file

@ -1,3 +1,50 @@
/** var path = require('path');
* Created by 608234548 on 10/04/2017. // Require WebpackAutoInject from npm installed modules ( prefered )
*/ // 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
}
})
]
};

984
dist/WebpackAutoInjectVersion.js vendored Normal file
View file

@ -0,0 +1,984 @@
(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;
console.log('------------------- INJECT BY TAG! ------------------');
this.context.compiler.plugin('emit', function (compilation, cb) {
console.log('------------------- INJECT BY TAG! APPLY! ------------------');
console.log(compilation.assets);
// for every output file
for (var basename in compilation.assets) {
console.log(_chalk2.default.green.bold('================='));
console.log(basename);
// only if match regex
console.log(basename + ' is: ' + _this.context.config.componentsOptions.InjectByTag.fileRegex.test(basename));
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 () {
console.log('replace?!');
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");
/***/ })
/******/ ]);
});

472
dist/index-bundle.js vendored
View file

@ -1,472 +0,0 @@
/******/ (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 = 11);
/******/ })
/************************************************************************/
/******/ ([
/* 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, __webpack_require__) {
"use strict";
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'
}
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Utils = function () {
function Utils() {
(0, _classCallCheck3.default)(this, Utils);
}
(0, _createClass3.default)(Utils, null, [{
key: 'isArgv',
value: function 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
*/
}, {
key: 'merge',
value: 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;
}
}]);
return Utils;
}();
module.exports = Utils;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("chalk");
/***/ }),
/* 5 */
/***/ (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 _chalk = __webpack_require__(4);
var _chalk2 = _interopRequireDefault(_chalk);
var _fs = __webpack_require__(8);
var _fs2 = _interopRequireDefault(_fs);
var _path = __webpack_require__(10);
var _path2 = _interopRequireDefault(_path);
var _config = __webpack_require__(2);
var _config2 = _interopRequireDefault(_config);
var _utils = __webpack_require__(3);
var _utils2 = _interopRequireDefault(_utils);
var _log = __webpack_require__(6);
var _log2 = _interopRequireDefault(_log);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var WebpackAutoInject = function () {
/**
* Constructor,
* called on webpack config load
* @param options
*/
function WebpackAutoInject(options) {
(0, _classCallCheck3.default)(this, WebpackAutoInject);
this.options = _utils2.default.merge(WebpackAutoInject.options, options);
var packageFile = JSON.parse(_fs2.default.readFileSync(_path2.default.normalize(_config2.default.PATH_PACKAGE), 'utf8'));
this.version = packageFile.version;
_log2.default.call('info', 'AIS_START');
this.executeNoneWebpackComponents();
}
/**
* Webpack apply call,
* when webpack is initialized and
* plugin has been called by webpack
* @param compiler
*/
/**
* Default options
*/
(0, _createClass3.default)(WebpackAutoInject, [{
key: 'apply',
value: function apply(compiler) {
this.compiler = compiler;
this.executeWebpackComponents();
}
/**
* Execute none webpack components
* - runs as soon as possible,
* > without waiting for webpack init
*/
}, {
key: 'executeNoneWebpackComponents',
value: function executeNoneWebpackComponents() {
this.executeComponents(_config2.default.NON_WEBPACK_COMPONENTS, function () {});
}
/**
* Execute webpack components
* - runs when webpack is initialized
* and plugins is called by webpack
*/
}, {
key: 'executeWebpackComponents',
value: function executeWebpackComponents() {
this.executeComponents(_config2.default.WEBPACK_COMPONENTS, function () {});
}
/**
* Execute components,
* - general layer for comp execution
* - used for both, webpack and non webpack comp
*/
}, {
key: 'executeComponents',
value: function executeComponents(components, done) {
var _this = this;
// no more components,
// finish
if (!components.length) {
done();return;
}
// take first component
var comp = components.shift();
// if component is disabled, call next component
if (!this.options[comp.option]) {
this.executeComponents(components, done);
return;
}
// execute component
var inst = new (!(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()))(this);
inst.apply().then(function () {
_this.executeComponents(components, done);
}, function (err) {
_this.executeComponents(components, done);
});
}
}]);
return WebpackAutoInject;
}();
WebpackAutoInject.options = {
autoIncrease: true,
injectAsComment: true,
injectByTag: true,
injectByTagFileRegex: /^index\.html$/
};
exports.default = WebpackAutoInject;
/***/ }),
/* 6 */
/***/ (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__(2);
var _config2 = _interopRequireDefault(_config);
var _chalk = __webpack_require__(4);
var _chalk2 = _interopRequireDefault(_chalk);
var _utils = __webpack_require__(3);
var _utils2 = _interopRequireDefault(_utils);
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 (u.isArgv('aiv-log-full')) {
this.logLevel = 3;
} else if (u.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();
/***/ }),
/* 7 */
/***/ (function(module, exports) {
function webpackEmptyContext(req) {
throw new Error("Cannot find module '" + req + "'.");
}
webpackEmptyContext.keys = function() { return []; };
webpackEmptyContext.resolve = webpackEmptyContext;
module.exports = webpackEmptyContext;
webpackEmptyContext.id = 7;
/***/ }),
/* 8 */
/***/ (function(module, exports) {
module.exports = require("fs");
/***/ }),
/* 9 */
/***/ (function(module, exports) {
module.exports = require("os");
/***/ }),
/* 10 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(5);
/***/ })
/******/ ]);

View file

@ -1,9 +1,9 @@
{ {
"name": "webpack-auto-inject-version", "name": "webpack-auto-inject-version",
"version": "0.2.0", "version": "0.5.0",
"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": {
"start": "babel-node tools/compile.js" "start": "babel-node tools/compile.js"
}, },
@ -30,7 +30,10 @@
}, },
"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;

View file

@ -1,24 +1,16 @@
module.exports = { export default {
NAME : 'Auto Inject Version', PACKAGE_JSON_PATH: './package.json',
SHORT : 'AIV', components: {
PATH_PACKAGE : './package.json', AutoIncreaseVersion: true,
NON_WEBPACK_COMPONENTS : [ InjectAsComment: true,
{ InjectByTag: true
option : 'autoIncrease',
path : './components/auto-inc-version'
}
],
WEBPACK_COMPONENTS : [
{
option : 'injectByTag',
path : './components/inject-by-tag'
}, },
{ componentsOptions: {
option : 'injectAsComment', InjectByTag: {
path : './components/inject-as-comment' fileRegex: /\.+/
} }
], },
LOGS_TEXT: { LOGS_TEXT: {
AIS_START: 'Auto inject version started' AIS_START: 'Auto inject version started'
} }
} };

View file

@ -1,9 +1,8 @@
import config from 'config'; import config from 'config';
import chalk from 'chalk'; import chalk from 'chalk';
import utils from 'core/utils'; import { isArgv } from 'core/utils';
const endOfLine = require('os').EOL; const endOfLine = require('os').EOL;
class Log{ class Log{
logLevel = 3; // default 1 logLevel = 3; // default 1
@ -13,9 +12,9 @@ class Log{
} }
getLogLevel() { getLogLevel() {
if(u.isArgv('aiv-log-full')){ if(isArgv('aiv-log-full')){
this.logLevel = 3; this.logLevel = 3;
}else if(u.isArgv('aiv-log-none')) { }else if(isArgv('aiv-log-none')) {
this.logLevel = 0; this.logLevel = 0;
} }
} }

View file

@ -1,9 +1,15 @@
class Utils{ let argv = require('optimist').argv;
static isArgv(arg) { /**
return Boolean(process.argv.find(function(item) { * Get argv from webpack env[argv]
return item.substr(0, 2) === '--' && item.indexOf(arg) > -1; * 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]);
} }
/** /**
@ -12,13 +18,11 @@ class Utils{
* @param obj2 * @param obj2
* @returns obj3 a new object based on obj1 and obj2 * @returns obj3 a new object based on obj1 and obj2
*/ */
static merge(obj1,obj2){ export function merge(obj1,obj2){
var obj3 = {}; var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; } for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; } for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3; return obj3;
} }
}
module.exports = Utils;

View file

@ -2,43 +2,56 @@ import chalk from 'chalk';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import config from 'config'; import config from 'config';
import u from 'core/utils';
import log from 'core/log'; 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{ export default class WebpackAutoInject{
/** static protectedConfig = {
* Default options NAME: 'Auto Inject Version',
*/ SHORT: 'AIV',
static options = {
autoIncrease: true,
injectAsComment: true,
injectByTag: true,
injectByTagFileRegex: /^index\.html$/
}; };
/** /**
* Constructor, * Constructor,
* called on webpack config load * called on webpack config load
* @param options * @param userConfig - config from the webpack config file
*/ */
constructor(options) { constructor(userConfig) {
this.options = u.merge(WebpackAutoInject.options, options); this.setConfig(userConfig);
let packageFile = JSON.parse(fs.readFileSync(path.normalize(config.PATH_PACKAGE), 'utf8')); let packageFile = JSON.parse(
fs.readFileSync(path.resolve(this.config.PACKAGE_JSON_PATH), 'utf8')
);
this.version = packageFile.version; this.version = packageFile.version;
log.call('info', 'AIS_START'); log.call('info', 'AIS_START');
this.executeNoneWebpackComponents(); 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, * Webpack apply call,
* when webpack is initialized and * when webpack is initialized and
* plugin has been called by webpack * plugin has been called by webpack
* @param compiler * @param compiler
*/ */
apply(compiler) { async apply(compiler) {
this.compiler = compiler; this.compiler = compiler;
this.executeWebpackComponents(); await this.executeWebpackComponents();
} }
/** /**
@ -46,9 +59,8 @@ export default class WebpackAutoInject{
* - runs as soon as possible, * - runs as soon as possible,
* > without waiting for webpack init * > without waiting for webpack init
*/ */
executeNoneWebpackComponents() { async executeNoneWebpackComponents() {
this.executeComponents(config.NON_WEBPACK_COMPONENTS, () => { await this.executeComponent([AutoIncreaseVersion]);
});
} }
/** /**
@ -56,9 +68,8 @@ export default class WebpackAutoInject{
* - runs when webpack is initialized * - runs when webpack is initialized
* and plugins is called by webpack * and plugins is called by webpack
*/ */
executeWebpackComponents() { async executeWebpackComponents() {
this.executeComponents(config.WEBPACK_COMPONENTS, () => { await this.executeComponent([InjectAsComment, InjectByTag]);
});
} }
/** /**
@ -66,25 +77,30 @@ export default class WebpackAutoInject{
* - general layer for comp execution * - general layer for comp execution
* - used for both, webpack and non webpack comp * - used for both, webpack and non webpack comp
*/ */
executeComponents(components, done) { async executeComponent(components) {
// no more components, // no more components,
// finish // finish
if(!components.length) { done(); return;} if(!components.length) {
return;
}
// take first component // take first component class
let comp = components.shift(); let ComponentClass = components.shift();
// if component is disabled, call next component // if component is disabled, call next component
if(!this.options[comp.option]) { if (!this.config.components[ComponentClass.componentName.toLowerCase()]) {
this.executeComponents(components, done); await this.executeComponent(components);
return; return;
} }
// execute component // execute component
let inst = new (require(comp.path))(this); let inst = new ComponentClass(this);
inst.apply().then(() => {
this.executeComponents(components, done); // await for apply to finish
}, (err) => {this.executeComponents(components, done);}) await inst.apply();
// call next tick
await this.executeComponent(components);
} }
} }

View file

@ -5,17 +5,14 @@ import nodeExternals from 'webpack-node-externals';
export default { export default {
target: 'node', target: 'node',
externals: [nodeExternals()], externals: [nodeExternals()],
entry: { entry: './src/main.js',
index: [
'./src/main.js'
]
},
resolve: { resolve: {
extensions: ['.js'] extensions: ['.js']
}, },
output: { output: {
filename: '[name]-bundle.js', filename: 'WebpackAutoInjectVersion.js',
path: path.resolve(process.cwd(), 'dist') path: path.resolve(process.cwd(), 'dist'),
libraryTarget: 'umd'
}, },
module: { module: {
// rules: [ // rules: [