Javascript-форум (https://javascript.ru/forum/)
-   Оффтопик (https://javascript.ru/forum/offtopic/)
-   -   Обсуждений тред (https://javascript.ru/forum/offtopic/47364-obsuzhdenijj-tred.html)

Erolast 10.07.2015 16:44

Цитата:

имею ввиду без трансляции запускать на ноде) Есть такое? Мне модули, классы оч. нужны)
Вместе с babel устанавливается утилита babel-node, аналогичная по функционалу простому node, но транспилящая перед запуском, запускай ею:
//package.json
{
  dependencies: {
    "babel": "^5.0.0"
  },
  scripts: {
    "start": "babel-node ./index.js"
  }
}

Код:

$ npm run start

Второй вариант - использовать require hook (тогда можно запускать просто через node):
//index.js
require("babel/register");
require("./server");

Babel подменит глобальную функцию require своей собственной, которая перед запуском модулей будет их предварительно транспиллить.

В обоих случаях рекомендуется создать в корне проекта JSON-файл с именем .babelrc и заблокировать там фичи, которые уже поддерживаются используемой платформой.

Мой файл для io.js выглядит так (может, уже устарел):
{
    "blacklist": [
        "es6.classes",
        "es6.blockScoping",
        "es6.constants",
        "es6.forOf",
        "es6.templateLiterals",
        "es6.properties.computed",
        "es6.properties.shorthand",
        "regenerator"
    ]
}


Цитата:

как быть, если я хочу импортить модули в gulpfile.js?)
//package.json
{
  dependencies: {
    "babel": "^5.0.0",
    "gulp": "^3.0.0"
  },
  scripts: {
    "gulp": "gulp --require babel/register"
  }
}

Код:

$ npm run gulp <task> -- <flags>

nerv_ 10.07.2015 21:54

Erolast, спасибо. Для меня представляли большую ценность в т.ч. модули es6.

Попытался использовать webpack, результат - сборка начинается, но в процессе подъема зависимостей gulp падает с ошибками
// gulpfile.es6

import gulp from './node_modules/gulp/index.js';

// webpack.gulpfile.js

module.exports = {
    entry: './gulpfile.es6',
    output: {
        path: './',
        filename: 'gulpfile.js'
    },
    module: {
        loaders: [
            // [url]https://github.com/babel/babel-loader[/url]
            {test: /\.es6$/, loader: 'babel'}
        ]
    }
};

> webpack.cmd --progress --colors --config webpack.gulpfile.js

Hash: 1d2c31565f3bb2097d35
Version: webpack 1.10.1
Time: 31356ms
      Asset    Size  Chunks             Chunk Names
gulpfile.js  900 kB       0  [emitted]  main
    + 202 hidden modules

WARNING in ./~/gulp/~/vinyl-fs/~/graceful-fs/fs.js
Critical dependencies:
11:12-19 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/gulp/~/vinyl-fs/~/graceful-fs/fs.js 11:12-19

WARNING in ./~/gulp/~/vinyl-fs/~/graceful-fs/package.json
Module parse failed: MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\graceful-fs\package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "author": {
|     "name": "Isaac Z. Schlueter",
|     "email": "i@izs.me",
 @ ./~/gulp/~/vinyl-fs/~/graceful-fs ^\.\/.*$

WARNING in ./~/gulp/~/vinyl-fs/~/graceful-fs/LICENSE
Module parse failed: MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\graceful-fs\LICENSE Line 1: Unexpected identifier
You may need an appropriate loader to handle this file type.
| The ISC License
| 
| Copyright (c) Isaac Z. Schlueter and Contributors
 @ ./~/gulp/~/vinyl-fs/~/graceful-fs ^\.\/.*$

WARNING in ./~/gulp/~/vinyl-fs/~/graceful-fs/README.md
Module parse failed: MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\graceful-fs\README.md Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
| # graceful-fs
| 
| graceful-fs functions as a drop-in replacement for the fs module,
 @ ./~/gulp/~/vinyl-fs/~/graceful-fs ^\.\/.*$

WARNING in ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch/minimatch.js
Critical dependencies:
6:5-12 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch/minimatch.js 6:5-12

WARNING in ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch/package.json
Module parse failed: MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-watcher\node_modules\gaze\node_modules\globule\node_modules\minimatch\packa
ge.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "author": {
|     "name": "Isaac Z. Schlueter",
|     "email": "i@izs.me",
 @ ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch ^\.\/.*$

WARNING in ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch/README.md
Module parse failed: MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-watcher\node_modules\gaze\node_modules\globule\node_modules\minimatch\READM
E.md Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
| # minimatch
| 
| A minimal matching utility.
 @ ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch ^\.\/.*$

WARNING in ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch/LICENSE
Module parse failed: MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-watcher\node_modules\gaze\node_modules\globule\node_modules\minimatch\LICEN
SE Line 1: Unexpected number
You may need an appropriate loader to handle this file type.
| Copyright 2009, 2010, 2011 Isaac Z. Schlueter.
| All rights reserved.
| 
 @ ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/~/globule/~/minimatch ^\.\/.*$

ERROR in ./~/gulp-util/~/beeper/index.js
Module parse failed: MY_PATH\node_modules\gulp-util\node_modules\beeper\index.js Line 9: Illegal return statement
You may need an appropriate loader to handle this file type.
|       process.argv.indexOf('--beep=false') !== -1) {
|       module.exports = function () {};
|       return;
| }
| 
 @ ./~/gulp-util/index.js 9:8-25

ERROR in ./~/gulp/~/vinyl-fs/lib/dest/writeContents/index.js
Module not found: Error: Cannot resolve module 'fs' in MY_PATH\node_modules\gulp\node_modules\vinyl-fs\lib\dest\writeContents
 @ ./~/gulp/~/vinyl-fs/lib/dest/writeContents/index.js 3:9-22

ERROR in ./~/gulp-util/~/vinyl/~/clone-stats/index.js
Module not found: Error: Cannot resolve module 'fs' in MY_PATH\node_modules\gulp-util\node_modules\vinyl\node_modules\clone-stats
 @ ./~/gulp-util/~/vinyl/~/clone-stats/index.js 1:11-24

ERROR in ./~/gulp/~/vinyl-fs/~/mkdirp/index.js
Module not found: Error: Cannot resolve module 'fs' in MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\mkdirp
 @ ./~/gulp/~/vinyl-fs/~/mkdirp/index.js 2:9-22

ERROR in ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/lib/gaze.js
Module not found: Error: Cannot resolve module 'fs' in MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-watcher\node_modules\gaze\lib
 @ ./~/gulp/~/vinyl-fs/~/glob-watcher/~/gaze/lib/gaze.js 14:9-22

ERROR in ./~/gulp/~/vinyl-fs/~/graceful-fs/fs.js
Module not found: Error: Cannot resolve module 'module' in MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\graceful-fs
 @ ./~/gulp/~/vinyl-fs/~/graceful-fs/fs.js 5:10-27

ERROR in ./~/gulp/~/vinyl-fs/~/vinyl/~/clone-stats/index.js
Module not found: Error: Cannot resolve module 'fs' in MY_PATH\node_modules\gulp\node_modules\vinyl-fs\node_modules\vinyl\node_modules\clone-stats
 @ ./~/gulp/~/vinyl-fs/~/vinyl/~/clone-stats/index.js 1:11-24

...

Erolast 11.07.2015 09:33

Цитата:

import gulp from './node_modules/gulp/index.js';
ES6-модули транспилятся в обычный нодовский require, так что можно просто import "gulp" from "gulp".

Цитата:

Попытался использовать webpack, результат - сборка начинается, но в процессе подъема зависимостей gulp падает с ошибками
Во-первых, для сборки бэкэнда нужно установить свойство target в конфиге вебпака на node.

Во-вторых, не все npm-овские модули можно просто так взять и забундлить. Проблема в том, что нативная нодовская система модулей допускает большое количество хаков, от части из которых у вебпака едет крыша (как, например, от ретурна из внешнего кода), так что тут либо разбираться с каждой ошибкой в отдельности, либо забить и запретить бундлинг node_modules:
"use strict";
let fs = require("fs");

module.exports = {
    entry: './gulpfile.es6',
    target: "node",
    *!*externals: fs.readdirSync('node_modules')*/!*,
    output: {
        path: './',
        filename: 'gulpfile.js',
        *!*libraryTarget: "commonjs"*/!*
    },
    module: {
        loaders: [
            {test: /\.es6$/, loader: 'babel'}
        ]
    }
};

nerv_ 12.07.2015 10:17

Erolast, большое спасибо! :)

тут собрал в кучу

KosBeg 13.07.2015 12:59

общем у меня есть способ сделать выборку елементов по класах(в условии отсутствия querySelectorAll и getElementsByClassName) в три раза быстрее чем в jquery, стоит ли сделать пул-риквест в sizzle?
http://i.imgur.com/YLWYhIl.png

KosBeg 13.07.2015 13:13

а вот скрин с файрфокса 39 - http://i.imgur.com/lfCIJCP.png
тоже в среднем выигрывает sizzle в два с половиной раза :dance:

Erolast 13.07.2015 14:41

Цитата:

выигрывает sizzle
Да ну? А в бенчмарке
Цитата:

jquery-1.11.2.js

KosBeg 13.07.2015 15:24

Последняя версия "sizzle.js" только-что скачаная с github, а "sizzle_old.js" найден в том же архиве
http://i.imgur.com/IiADcla.png
Вам таки легче стало? ;)
Щас кину скрин с восьмого осла
PS: я напомню еще раз - это результаты когда нету QSA и getElementsByClassName,
"блокирую" их я так
<script type="text/javascript">
  document.querySelectorAll = undefined;
  document.getElementsByClassName = undefined;
</script>

А с QSA и getElementsByClassName результаты у всех не больше 2мс ;)

KosBeg 13.07.2015 15:42

скрин-доказательство с 8 осла
 
Вложений: 2
вот скрин с восьмого козла осла

nerv_ 13.07.2015 16:27

Цитата:

Сообщение от KosBeg
скрин-доказательство с 8 осла

забудь о нем, он умер :)


Часовой пояс GMT +3, время: 10:10.