Error in plugin gulp babel

I'm trying to use JavaScript 2015 (ES6) now in my Ionic v1 app: package.json { "name": "test", "version": "1.0.0", "dependencies": { "@ionic-native/deeplinks": "^4.18.0", "cordova-

I’m trying to use JavaScript 2015 (ES6) now in my Ionic v1 app:

package.json

 {
  "name": "test",
  "version": "1.0.0",
  "dependencies": {
    "@ionic-native/deeplinks": "^4.18.0",
    "cordova-android": "7.0.0",
    "cordova-android-support-gradle-release": "1.2.1",
    "cordova-common": "1.5.1",
    "cordova-plugin-app-event": "1.2.1",
    "cordova-plugin-camera": "4.0.2",
    "cordova-plugin-datepicker": "git+https://github.com/VitaliiBlagodir/cordova-plugin-datepicker.git",
    "cordova-plugin-device": "2.0.1",
    "cordova-plugin-google-analytics": "1.7.11",
    "cordova-plugin-inappbrowser": "2.0.2",
    "cordova-plugin-network-information": "2.0.1",
    "cordova-plugin-splashscreen": "5.0.2",
    "cordova-plugin-whitelist": "1.3.3",
    "cordova-plugin-x-socialsharing": "5.3.2",
    "de.appplant.cordova.plugin.local-notification": "0.8.5",
    "es6-promise-plugin": "4.2.2",
    "ionic-native": "^2.9.0",
    "ionic-plugin-deeplinks": "^1.0.17",
    "ionic-plugin-keyboard": "2.2.1",
    "parse-push-plugin": "^1.0.7"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "babel-loader": "^7.1.5",
    "babel-preset-es2015": "^6.24.1",
    "bower": "1.3.3",
    "gulp": "3.8.10",
    "gulp-babel": "^8.0.0",
    "gulp-concat": "2.2.0",
    "gulp-minify-css": "0.3.0",
    "gulp-plumber": "^1.2.1",
    "gulp-rename": "1.2.0",
    "gulp-sass": "2.2.0",
    "gulp-util": "2.2.14",
    "ionic-minify": "2.0.10",
    "shelljs": "0.3.0"
  },
  "cordovaPlugins": [
    "cordova-plugin-inappbrowser",
    "cordova-plugin-whitelist",
    "cordova-plugin-splashscreen",
    "cordova-plugin-camera",
    "cordova-plugin-x-socialsharing",
    "ionic-plugin-keyboard",
    "cordova-plugin-datepicker",
    "cordova-plugin-network-information",
    "de.appplant.cordova.plugin.local-notification",
    "parse-push-plugin@1.0.7",
    "cordova-plugin-google-analytics@1.7.11",
    "cordova-custom-config",
    "ionic-plugin-deeplinks"
  ],
  "cordovaPlatforms": [
    "android"
  ],
  "cordova": {
    "plugins": {
      "cordova-plugin-datepicker": {},
      "cordova-plugin-network-information": {},
      "cordova-plugin-inappbrowser": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-camera": {},
      "cordova-plugin-x-socialsharing": {},
      "ionic-plugin-keyboard": {},
      "de.appplant.cordova.plugin.local-notification": {},
      "cordova-android-support-gradle-release": {
        "ANDROID_SUPPORT_VERSION": "26"
      },
      "parse-push-plugin": {},
      "cordova-plugin-google-analytics": {},
    },
    "platforms": []
  }
}

gulpfile.js:

var gulp = require('gulp');
var babel = require("gulp-babel");
var plumber = require("gulp-plumber");
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');

var paths = {
  es6: ['./src/es6/*.js'],
  sass: ['./scss/**/*.scss']
};

gulp.task('default', ['babel', 'sass']);

gulp.task("babel", function () {
  return gulp.src(paths.es6)
    .pipe(plumber())
    .pipe(babel({presets: ['es2015']}))
    .pipe(gulp.dest("www/js"));
});

gulp.task('sass', function(done) {
    gulp.src('./scss/ionic.app.scss')
      .pipe(sass())
      .pipe(gulp.dest('./www/css/'))
      .pipe(minifyCss({
        keepSpecialComments: 0
      }))
      .pipe(rename({ extname: '.min.css' }))
      .pipe(gulp.dest('./www/css/'))
      .on('end', done);
  });


gulp.task('watch', function() {
  gulp.watch(paths.es6, ['babel']);
  gulp.watch(paths.sass, ['sass']);
});

And while running «gulp babel» I’m getting the following error:

Error in plugin "gulp-babel"
Message:
    Plugin/Preset files are not allowed to export objects, only functions.

I’m pretty sure that it is related to wrong versions in devDependencies.

I tried to change version, but keep getting errors.

I would really appreciate if someone can help me solve this issue.

Начал изучать JavaScript по книге «Learning JavaScript. 3rd Edition. O’Reilly». И не смотря на то, что делал всё в точности как там написано, получаю ошибки вместо ожидаемого результата.

SyntaxError in plugin «gulp-babel»
Message:
C:Usersarchitestljpublices6test.js: Unexpected token, expected «,» (4:44)

package.json

"devDependencies": {
    "@babel/cli": "^7.5.5",
    "@babel/core": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/register": "^7.5.5",
    "babel": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0"
  }

test.js

'use strict';
// es6 feature: block-scoped "let" declaration
const sentences = [
	{ subject: 'JavaScript', verb: 'is', object: 'great' },
	{ subject: 'Elephants', verb: 'are', object: 'large' },
];
// es6 feature: object destructuring
function say({ subject, verb, object }) {
	//es 6 feature: template strings
	console.log(`${subject} ${verb} ${object}`);
}
//es6 feature for..of
for(let s of sentences) {
	say(s);
}

gulpfile.babel.js

const gulp = require('gulp');
const babel = require('gulp-babel');

gulp.task('default', function() {
	
	gulp.src("es6/**/*.js")
		.pipe(babel())
		.pipe(gulp.dest("dist"));
		
	gulp.src("public/es6/**/*.js")
		.pipe(babel())
		.pipe(gulp.dest("public/dist"))
});

0 / 0 / 0

Регистрация: 07.07.2019

Сообщений: 2

1

30.07.2019, 18:05. Показов 1282. Ответов 0


Совсем недавно начал изучать JavaScript по книге «Learning JavaScript. 3rd Edition» Издательство O’Reilly по началу всё шло хорошо (почти) и гладко, пока не дошёл до момента где нужно работать с npm и gulp-babel. Сначала выдало одну ошибку, с ней кое-как разобрался, а теперь вот другая.
Судя по тому, что в книге — gulp-babel должен
1) код из файла .js написанный по стандарту es6 перевести в стандарт es5
2) при этом скопировав файл .js в директорию public/dist
но по факту, когда пишу команду gulp консоль выдаёт ошибку

SyntaxError in plugin «gulp-babel»
Message:
C:Usersarchitestljpublices6test.js: Unexpected token

Мне даже пришлось хоть немного разобраться в устройстве компайлеров для того, чтобы хоть немного приблизиться к решению этой проблемы. Если я правильно понял транспайлер выдаёт ошибку на уровне лексического анализа и никак не могу понять почему? Буду весьма признателен, если поможете.

Вот package.json

JSON
1
2
3
4
5
6
7
8
9
10
11
 "devDependencies": {
    "@babel/cli": "^7.5.5",
    "@babel/core": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/register": "^7.5.5",
    "babel": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0"
  }
}

gulpfile.babel.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const gulp = require('gulp');
const babel = require('gulp-babel');
const register = require('@babel/register');
 
gulp.task('default', function() {
    
    gulp.src("es6/**/*.js")
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(gulp.dest("dist"));
        
    gulp.src("public/es6/**/*.js")
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(gulp.dest("public/dist"))
});

test.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'use strict';
// es6 feature: block-scoped "let" declaration
const sentences = [
    { subject: 'JavaScript', verb: 'is', object: 'great' },
    { subject: 'Elephants', verb: 'are', object: 'large' },
];
// es6 feature: object destructuring
function say({ subject, verb, object }) {
    //es 6 feature: template strings
    console.log(`${subject} ${verb} ${object}`);
}
//es6 feature for..of
for(let s of sentences) {
    say(s);
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Сейчас я пытаюсь использовать JavaScript 2015 (ES6) в своем приложении Ionic v1:

Пакет.json

 {
  "name": "test",
  "version": "1.0.0",
  "dependencies": {
    "@ionic-native/deeplinks": "^4.18.0",
    "cordova-android": "7.0.0",
    "cordova-android-support-gradle-release": "1.2.1",
    "cordova-common": "1.5.1",
    "cordova-plugin-app-event": "1.2.1",
    "cordova-plugin-camera": "4.0.2",
    "cordova-plugin-datepicker": "git+https://github.com/VitaliiBlagodir/cordova-plugin-datepicker.git",
    "cordova-plugin-device": "2.0.1",
    "cordova-plugin-google-analytics": "1.7.11",
    "cordova-plugin-inappbrowser": "2.0.2",
    "cordova-plugin-network-information": "2.0.1",
    "cordova-plugin-splashscreen": "5.0.2",
    "cordova-plugin-whitelist": "1.3.3",
    "cordova-plugin-x-socialsharing": "5.3.2",
    "de.appplant.cordova.plugin.local-notification": "0.8.5",
    "es6-promise-plugin": "4.2.2",
    "ionic-native": "^2.9.0",
    "ionic-plugin-deeplinks": "^1.0.17",
    "ionic-plugin-keyboard": "2.2.1",
    "parse-push-plugin": "^1.0.7"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "babel-loader": "^7.1.5",
    "babel-preset-es2015": "^6.24.1",
    "bower": "1.3.3",
    "gulp": "3.8.10",
    "gulp-babel": "^8.0.0",
    "gulp-concat": "2.2.0",
    "gulp-minify-css": "0.3.0",
    "gulp-plumber": "^1.2.1",
    "gulp-rename": "1.2.0",
    "gulp-sass": "2.2.0",
    "gulp-util": "2.2.14",
    "ionic-minify": "2.0.10",
    "shelljs": "0.3.0"
  },
  "cordovaPlugins": [
    "cordova-plugin-inappbrowser",
    "cordova-plugin-whitelist",
    "cordova-plugin-splashscreen",
    "cordova-plugin-camera",
    "cordova-plugin-x-socialsharing",
    "ionic-plugin-keyboard",
    "cordova-plugin-datepicker",
    "cordova-plugin-network-information",
    "de.appplant.cordova.plugin.local-notification",
    "parse-push-plugin@1.0.7",
    "cordova-plugin-google-analytics@1.7.11",
    "cordova-custom-config",
    "ionic-plugin-deeplinks"
  ],
  "cordovaPlatforms": [
    "android"
  ],
  "cordova": {
    "plugins": {
      "cordova-plugin-datepicker": {},
      "cordova-plugin-network-information": {},
      "cordova-plugin-inappbrowser": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-camera": {},
      "cordova-plugin-x-socialsharing": {},
      "ionic-plugin-keyboard": {},
      "de.appplant.cordova.plugin.local-notification": {},
      "cordova-android-support-gradle-release": {
        "ANDROID_SUPPORT_VERSION": "26"
      },
      "parse-push-plugin": {},
      "cordova-plugin-google-analytics": {},
    },
    "platforms": []
  }
}

Gulpfile.js:

var gulp = require('gulp');
var babel = require("gulp-babel");
var plumber = require("gulp-plumber");
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');

var paths = {
  es6: ['./src/es6/*.js'],
  sass: ['./scss/**/*.scss']
};

gulp.task('default', ['babel', 'sass']);

gulp.task("babel", function () {
  return gulp.src(paths.es6)
    .pipe(plumber())
    .pipe(babel({presets: ['es2015']}))
    .pipe(gulp.dest("www/js"));
});

gulp.task('sass', function(done) {
    gulp.src('./scss/ionic.app.scss')
      .pipe(sass())
      .pipe(gulp.dest('./www/css/'))
      .pipe(minifyCss({
        keepSpecialComments: 0
      }))
      .pipe(rename({ extname: '.min.css' }))
      .pipe(gulp.dest('./www/css/'))
      .on('end', done);
  });


gulp.task('watch', function() {
  gulp.watch(paths.es6, ['babel']);
  gulp.watch(paths.sass, ['sass']);
});

И при запуске «gulp babel» я получаю следующую ошибку:

Error in plugin "gulp-babel"
Message:
    Plugin/Preset files are not allowed to export objects, only functions.

Я почти уверен, что это связано с неправильными версиями в devDependencies.

Я пытался изменить версию, но продолжаю получать ошибки.

Я был бы очень признателен, если бы кто-нибудь помог мне решить эту проблему.

thumb

Recently, when attempting to install the gulp-babel package using the npm CLI (“Node package manager”, “Command line interface”) in the Terminal app, I saw a warning saying gulp-babel@8.0.0 requires a peer of @babel/core@^7.0.0. Then, when attempting to run gulp, I saw an error message saying that gulp run is failed because Cannot find module '@babel/core'. In this tutorial, you’ll learn how to solve this problem.

How to fix: npm WARN gulp-babel@8.0.0 requires a peer of @babel/core@

What causes this error

In my case, the below warning message appeared when attempting to install the gulp-babel package using the npm CLI (“Node package manager”, “Command line interface”) in the Terminal app.

$ npm install gulp-babel --save-dev
npm WARN gulp-babel@8.0.0 requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.

+ gulp-babel@8.0.0
added 2 packages from 5 contributors and audited 6639 packages in 3.529s

5 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

And the below error appeared when attempting to run the gulp command inside my app project.

$ gulp
internal/modules/cjs/loader.js:983
  throw err;
  ^

Error: Cannot find module '@babel/core'
Require stack:
- /Users/arthur/GitHub/app/node_modules/gulp-babel/index.js
- /Users/arthur/GitHub/app/gulpfile.js
- /usr/local/lib/node_modules/gulp-cli/lib/versioned/^4.0.0/index.js
- /usr/local/lib/node_modules/gulp-cli/index.js
- /usr/local/lib/node_modules/gulp-cli/bin/gulp.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
    at Function.Module._load (internal/modules/cjs/loader.js:862:27)
    at Module.require (internal/modules/cjs/loader.js:1040:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/Users/arthur/GitHub/app/node_modules/gulp-babel/index.js:7:15)
    at Module._compile (internal/modules/cjs/loader.js:1151:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
    at Module.load (internal/modules/cjs/loader.js:1000:32)
    at Function.Module._load (internal/modules/cjs/loader.js:899:14)
    at Module.require (internal/modules/cjs/loader.js:1040:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/arthur/GitHub/app/node_modules/gulp-babel/index.js',
    '/Users/arthur/GitHub/app/gulpfile.js',
    '/usr/local/lib/node_modules/gulp-cli/lib/versioned/^4.0.0/index.js',
    '/usr/local/lib/node_modules/gulp-cli/index.js',
    '/usr/local/lib/node_modules/gulp-cli/bin/gulp.js'
  ]
}

The warning and error message above are self explanatory. They saying that the gulp run is failed, and this is because it Cannot find module '@babel/core' and gulp-babel@8.0.0 requires a peer of @babel/core@^7.0.0 but none is installed accordingly. Therefore, we just need to install the dependencies ourself to solve the problem.

From the Babel documentation at babeljs.io/docs/en/next/usage:

All the Babel modules you will need are published as separate npm packages scoped under `@babel` (since version 7). This modular design allows for various tools each designed for a specific use case.

...

The core functionality of Babel resides at the `@babel/core` module.

Now we know what caused this error.

How to solve it

Once we know what is causing the gulp run to fail, we can use it to solve the problem. It is a really easy process. To solve this problem, we need to install the '@babel/core' and @babel/preset-env modules. Now, step by step guide.


Launch the Terminal app from the Utilities folder of your Applications folder, or use Spotlight to find it.

How to fix: npm WARN gulp-babel@8.0.0 requires a peer of @babel/core@


Go to the working directory (in this example the my_app_dir catalog is used) by typing the following command and press the Enter key.

Important! In my case the working directory is the catalog of my app project called my_app_dir where the problem has occurred. Change the command above to suit your case.


Type the following command and press the Enter key to install the '@babel/core' and @babel/preset-env modules inside your working directory.

npm install @babel/core @babel/preset-env --save-dev

+ @babel/core@7.8.4
+ @babel/preset-env@7.8.4
added 123 packages from 31 contributors and audited 8141 packages in 14.653s

8 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Finally, we can try to run gulp and verify that it runs without the error. For this, type the following command and press the Enter key.

Note! In the command below just the gulp is used. Change the command below to suit your case.

[03:26:53] Using gulpfile ~/my_app_dir/gulpfile.js
[03:26:53] Starting 'test'...
[03:26:53] Finished 'test' after 22 ms

No errors. It works!

Conclusion

That’s it, you’re done. Now the gulp should run without the npm WARN gulp-babel@8.0.0 requires a peer of @babel/core@ error. So simple isn’t it?

If you are having trouble fixing this problem with the instructions above, but are being able to solve this problem with any another method please describe it in the comment section below. Thanks!

I hope this article has helped you learn how to fix the node-gyp rebuild error. If this article has helped you then please leave a comment :smiley:

Thanks for reading!

arixse

how to disable the strict mode?

how to disable the strict mode?

loganfsmyth

@arixse The recommended approach would be to change your presets, e.g.

to be

presets: [
    ['es2015', {modules: false}]
]

note the new set of square brackets in there.

Babel code adds use strict automatically because es2015 by default expects code to be ES6 modules, which are strict by default.

cryoguy

I am always getting following error. Does it mean that it is still in strict mode?

Plumber found unhandled error:
SyntaxError in plugin ‘gulp-babel’
Message:
/../app/scripts/prettyphoto/js/jquery.prettyPhoto.js: Deleting local variable in strict mode (7:21327):

my gulpjs setting:

gulp.task(‘scripts’, () => {
return gulp.src(‘app/scripts/*/.js’)
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe(babel({
presets:[
[‘es2015’, {modules: false}]
]
}))
.pipe($.sourcemaps.write(‘.’))
.pipe(gulp.dest(‘.tmp/scripts’))
.pipe(reload({stream: true}));
});

hzoo

Closing this issue as it’s been inactive for several months. Please feel free to open a new issue or leave a comment asking to reopen this issue. Thanks! ✌️

If you just have an usage issue or want help, I would recommend checking out our slack community or StackOverflow.

djwashburn

Could you reopen this? I have the same problem as @cryoguy above — even with this setting, it fails on a complaint about deleting local variables in strict mode.

ahmedofali

Run this command :

 npm install --save-dev @babel/preset-es2015

then in the gulpfile add this

presets: [
        ['@babel/preset-env', {modules: false}]
]

sts-ryan-holton

This isn’t working, Gulp 3.9.1, my JS is:

gulp.task('build-plugin-js', () =>
  gulp.src([
    'src/js/plugin/script.js'
  ])
  .pipe(concat('les-inbound.js'))
  .pipe(babel({
    presets: ['@babel/preset-env', {modules: false}]
  }))
  .pipe(minify())
  .pipe(gulp.dest('public/dist/js/plugins/'))
);

nicolo-ribaudo

@sts-ryan-holton That’s not enough to reproduce the error. Can you post the full stack trace, the input code and the generated code?

maciej-gawlas

@sts-ryan-holton try to add additional brackets :
.pipe(babel({ presets: [['@babel/preset-env', {modules: false}]] }))

guilhermesantoss

Инструменты

Настройка Gulp Babel

Дата размещения статьи 20/10/2019 👁6379

Настройка Gulp Babel

Что такое Babel, зачем он нужен, как установить gulp-babel для Gulp, настроить и начать использовать в своих проектах.

Содержание:

  1. Babel для Gulp;
    1. установка gulp-babel;
    2. настройка gulpfile.js;
    3. создание babelrc;
    4. пример;
    5. итоговый код;
  2. gulp-terser;

Babel — это компилятор JavaScript. Содержит в себе набор инструментов,
позволяющих преобразовывать код ECMAScript 2015 и выше в совместимую версию JavaScript для более старых браузеров.

Использование Babel для Gulp

Установка и настройка Babel для Gulp

1. Установка gulp-babel в проект

Babel 7

npm install gulp-babel @babel/core @babel/preset-env --save-dev

2. Настройка gulpfile.js

.pipe(babel()) — используйте перед конкатенацией и минификацией.

const { src, dest, watch, series, parallel } = require("gulp");
const babel = require("gulp-babel");

function js() {
    return src([
        "app/assets/js/scripts.js"
    ])
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest("build/assets/js/"))
}

3. Создание конфигурационного файла .babelrc

Необходимо создать файл .babelrc со следующим содержимым:

{
    "presets": ["@babel/preset-env"]
}

Babel для Gulp успешно установлен и настроен, теперь у вас есть возможность использования ES6+ синтаксиса в своих проектах на Gulp.

4. Пример использования gulp-babel

Пример использования gulp-babel в реальном проекте:

const { src, dest, watch, series, parallel } = require("gulp");
const sourcemaps = require("gulp-sourcemaps"); // Source Maps
const babel = require("gulp-babel");
const concat = require("gulp-concat"); // объединение файлов в один

function scripts() {
    return src("app/assets/js/**/*.js")
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(concat("scripts.js"))
        .pipe(sourcemaps.write("."))
        .pipe(dest("build/assets/js/"))
}

exports.scripts = scripts;

exports.default = scripts;

5. Итоговый код за 4 статьи

Резюмируя предыдущие статьи по Gulp, получаем следующий gulpfile.js:

const { src, dest, watch, lastRun, series, parallel } = require("gulp");
const sass = require("gulp-sass");
const sourcemaps = require("gulp-sourcemaps");
const browserSync = require("browser-sync").create(); // сервер + перезагрузка
const babel = require("gulp-babel");                  // для работы с JS
const concat = require("gulp-concat");                // объединение файлов в один

function HTML() {
    return src("app/**/*.html", { since: lastRun(HTML) })
        .pipe(dest("dist/"))
        .pipe(browserSync.stream())
}
exports.HTML = HTML;

function SASS() {
    return src("app/assets/sass/**/*.sass")
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: "nested"
        }).on("error", sass.logError))
        .pipe(sourcemaps.write("."))
        .pipe(dest("app/assets/css/"))
        .pipe(dest("dist/assets/css/"))
        .pipe(browserSync.stream())
}
exports.SASS = SASS;

function scripts() {
    return src([
        "app/assets/js/script_1.js",
        "app/assets/js/script_2.js",
        "app/assets/js/main.js"
    ], { since: lastRun(HTML) })
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(concat("app.js"))
        .pipe(sourcemaps.write("."))
        .pipe(dest("app/assets/js/"))
        .pipe(dest("dist/assets/js/"))
        .pipe(browserSync.stream())
}
exports.scripts = scripts;

function myServer() {
    browserSync.init({
        server: {
            baseDir: "app" // папка для локального сервера
        },
        notify: false
    });

    watch("app/**/*.html", { usePolling: true }, HTML);            // следим за HTML
    watch("app/assets/sass/**/*.sass", { usePolling: true }, SASS) // следим за SASS
    watch("app/assets/js/**/*.js", { usePolling: true }, scripts)  // следим за JS
}

exports.default = series(HTML, SASS, scripts, myServer);

Использование gulp-terser

Возможно, вы решили воспользоваться gulp-babel, из-за того что вам порядком надоели ошибки: GulpUglifyError: unable to minify JavaScript :

  • Caused by: SyntaxError: Unexpected token: keyword «const»
  • Caused by: SyntaxError: Invalid assignment
  • Caused by: SyntaxError: Unexpected token: name «», expected: punc «;»

Тогда вы можете воспользоваться плагином gulp-terser с поддержкой ECMAScript 2015. ссылка.

Данный пакет сжимает (минифицирует) ES6+ код.

Статьи про Gulp:

  1. Что такое Gulp, зачем он нужен и как его использовать (1 часть).
  2. Использование SASS в Gulp (2 часть).
  3. Автоматическое обновление страницы с помощью browser-sync для Gulp (3 часть).
  4. Использование Babel в Gulp (4 часть — текущая).
  5. Моментальная загрузка сайта на хостинг и синхронизация файлов — gulp-rsync (5 часть).
Дата обновления статьи 05/01/2022 01:36

JavaScript: Информация О Нажатой Клавише 👇🏽 Валидация input

Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки,
то можете следить за выходом новых статей в Telegram.

  • Git SSH Windows — пошаговое руководство
  • Микроразметка сайта
  • Как перенести сайт WordPress на хостинг
  • Настройте показ всего текста во время загрузки веб-шрифтов
  • Сниппеты в VS Code
  • Не удается проверить так как не задан исполняемый PHP-файл

Понравилась статья? Поделить с друзьями:
  • Error in plots display expecting plot structure but received
  • Error in plot3d first argument must be either in standard or parametric form
  • Error in plot unexpected options
  • Error in plot unexpected option
  • Error in plot procedure expected as range contains no plotting variable