_

 

 

 

 

 

 

 

Modern

JavaScript

Tooling

WorkFlow Package Manager 

Node Package Manager

(пакетный менеджер node.js)

 

Он используется для скачивания пакетов из облачного сервера npm или загрузки.

 

для установки npm необходима установить Node.js

осн. команды

//-- Установка пакета
npm install grunt-contrib-concat // Локальная
npm install grunt-contrib-concat -g // Глобально
npm install grunt-contrib-concat@0.1.2 // Определённой версии пакета
npm install grunt-contrib-concat@"<0.5.0" // ниже указаной
npm install grunt-contrib-concat grunt-contrib-concat // Несколько пакетов
npm install grunt-contrib-concat --save // Локальная в dependencies
npm install grunt-contrib-concat --save-dev // Локальная в dependencies

//-- Удаление пакета
npm uninstall grunt-contrib-concat // Локальная

//-- Просмотр информации о пакете
npm view grunt-contrib-concat

//-- Cписка установленных пакетов
npm list

//-- Создание нового пакета
npm init

Сокращения

install i
uninstall r
config с
update up
list ls
--save- S
--save-dev -D

package.json

 

Файл package.json содержит в себе информацию о вашем приложении:

 название, версия, зависимости и тому подобное.​

 

Любая директория, в которой есть этот файл, интерпретируется как Node.js-пакет.

{
  "name": "grunt-overview",
  "version": "1.0.0",
  "description": "",
  "main": "builds/js/main.js", // entry point to your package
  "private": true,
  "dependencies": {
  },
  "devDependencies": {
    "grunt-contrib-copy": "^1.0.0",
    "grunt-contrib-concat": "^0.3.0",
    "grunt": "^0.4.5",
    "grunt-contrib-uglify": "^0.2.7",
    "grunt-contrib-watch": "^0.5.3"
  },
  "scripts": {
    "start": "grunt build && grunt watch",
    "watch": "grunt watch",
    "build": "grunt build"
  },
  "author": "Sarhan Azizov",
  "license": "ISC"
}

--save или --save-dev?

 

Компиляторы-трансляторы (типа Coffee, LESS, Jade), тест-раннеры, стайл-чекеры (mocha, chai, karma, (js|es)lint, jscs), плагины для таск-раннеров (grunt-contrib-watch, gulp-jade) — все это обычно ставится как --save-dev.

 

Библиотеки и фреймворки (expressjs, jquery, backbone), на основе которых работает ваш код, без которых ваш код не запустится у его потребителя — ставятся как --save.

 

Формат номера версии [major, minor, patch], где:

major  - продукт полностью готов (поддержка)

minor - продукт потерпел незначительные изменения

patch - номер сборки

{
  "name": "grunt-overview",
  "version": "1.0.0",
  "dependencies": {
  },
  "devDependencies": {
    "grunt-contrib-copy": "^1.0.0",
    "grunt-contrib-concat": "^0.3.0",
    "grunt": "^0.4.5",
    "grunt-contrib-uglify": "^0.2.7",
    "grunt-contrib-watch": "^0.5.3"
  },
  "scripts": {},
}

При изменении версии происходит обнуление по правой стороне.

Comparator

  • Ranges (<,<=,>,>=,=)1.2.7
  • Prerelease Tags: alpha/beta/rc 1.2.3-alpha.3
  • X-Ranges 1.2.x 1.X 1.2.* *
  • Tilde Ranges ~1.2.3 ~1.2 ~1
  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4
  • latest

 

{
  "name": "grunt-overview",
  "version": "1.0.0",
  "dependencies": {
  },
  "devDependencies": {
    "grunt-contrib-copy": "^1.0.0",
    "grunt-contrib-concat": "^0.3.0",
    "grunt": "^0.4.5",
    "grunt-contrib-uglify": "^0.2.7",
    "grunt-contrib-watch": "^0.5.3"
  },
  "scripts": {},
}

Bower

A package manager for the web

VS

Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.

project root
[bower_components] // default directory for dependencies
 -> dependency A
 -> dependency B // needs A
 -> dependency C // needs B and D
 -> dependency D

It is much harder to avoid dependency conflicts without nesting dependencies.

project root
[node_modules] // default directory for dependencies
 -> dependency A
 -> dependency B
    [node_modules]
    -> dependency A

 -> dependency C
    [node_modules]
    -> dependency B
      [node_modules]
       -> dependency A 
    -> dependency D

havy

  • Transcompiling JavaScript: CoffeeScript, Dart, Babel, Traceur etc.
  • JavaScript Transforms: wrapping in modules or ng-annotate etc.
  • Bundling/Concatenation: combining of scripts and styles into multiple files
  • Minification: scripts, styles and html
  • Source Maps: for both scripts and styles
  • CSS Preprocessor: Less, Sass, Stylus etc.
  • Style Transforms: Autoprefixer, PostCSS etc.
  • Cache Busting: renaming files with a hash to prevent incorrect caching
  • Image Optimization
  • Compiling Templates: Mustache or HandlebarsJS, Underscore, EJS, Jade etc.
  • Copying Assets: html, fav icon etc.
  • Watching for Changes
  • Incremental Rebuild
  • Clean Build: deleting all files at start or preferably cleaning up files as needed
  • Injecting References: generating script and style tags that reference the bundled files
  • Build Configurations: separate Dev, Test and Prod configuration, for example to not minify html in dev build
  • Serve: running a development web server
  • Running Unit Tests
  • Running JavaScript and CSS Linters: jshint, csslint etc.
  • Dependencies: handle dependencies on npm and Bower packages, Browserfy etc.

The JavaScript Task Runner

Позволяет сократить время на повторяющиеся задачи такие как: минификацию, компиляцию, юнит тестирование, статическую проверку кода и другое.

// Run the version of Grunt which has been installed.
npm install -g grunt-cli

// Installing Grunt 
npm install grunt --save-dev

// Installing gruntplugins
npm install grunt-contrib-uglify --save-dev

Available Grunt plugins (5,829)

Many of the tasks you need are already available as Grunt Plugins, and new plugins are published every day. While the plugin listing is more complete, here's a few you may have heard of.

example: grunt-overview

The streaming build system

// Install gulp cli
npm install -g gulp-cli

// Created package
npm init

// Install gulp 
npm i gulp -D

// Installing plugin
npm i gulp-uglify -D

API

// Provided files 

// -- gulp.src(globs[, options])
gulp.src('client/templates/*.jade')
gulp.src(['client/*.js', '!client/b*.js', 'client/bad.js'])
gulp.src('client/js/**/*.js')

// Re-emits all data passed to it so you can pipe to multiple folders

// -- gulp.dest(path[, options])
gulp.src('client/js/**/*.js', { base: 'client' })
  .pipe(concat())
  .pipe(gulp.dest('build')); // Writes 'build/js/somedir/somefile.js'
  .pipe(minify())
  .pipe(gulp.dest('build/prod')); // Writes 'build/prod/js/somedir/somefile.js'

// Define a task.

// -- gulp.task(name [, deps] [, fn])
gulp.task('scripts', ['clean'], function() {
    return gulp.src('app/js/**/*.js')
               .pipe(concat())
               .pipe(gulp.dest('build')); // build/js
});

// Watch files and do something when a file changes.

// -- gulp.watch(glob [, opts], tasks) or gulp.watch(glob [, opts, cb])
var watcher = gulp.watch('js/**/*.js', ['uglify','reload']);
watcher.on('change', function(event) {
  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});

example: gulp-overview

VS

  • More plugins
  • Config file as object
  • Faster
    • Works on streams
    • VFS no temp foder
    • parallelism
  • Has self API
  • compact config

WebPack

                                 Module Builder

// Installing WebPack
npm i webpack -g

// Installing npm package
npm init

// Installing webpack
npm i webpack -D

Deps: AMD, CommonJS, ES-2015

CommonsChunkPlugin

example: webpack-overview

Create Simple Project Architecture

Requirements

- Minification: scripts, styles and html

- Style Transforms: PostCSS etc.
- CSS Preprocessor: Less, Sass, Stylus etc.
- Image Optimization
- Compiling Templates: Mustache or HandlebarsJS, Underscore, EJS, Jade etc.
- Copying Assets: html, fav icon etc.
- Watching for Changes
- Clean Build: deleting all files at start or preferably cleaning up files as needed
- Build Configurations: separate Dev and Prod configuration, for example to not minify html in dev build
- Running JavaScript and CSS Linters: eslint, csslint etc.
- Dependencies: handle dependencies on npm and Bower packages etc.

More....

The End

Grunt, Gulp, Webpack, Npm etc.

By Sarhan Azizov

Grunt, Gulp, Webpack, Npm etc.

  • 573