Plugin/Preset files are not allowed to export objects, only functions. In [...]/babel-preset-es2015/lib/index.js - gulp

I am trying to get my asset bundling to work with es6 and it wont work. My package.json is:
"devDependencies": {
"babel-preset-es2015": "^6.6.0",
"del": "^2.2.0",
"gulp": "^3.9.1",
"gulp-babel": "^6.1.2"
}
My bundle.config.json conatins:
options: {
uglify: ['production'], // uglify the resulting bundle in prod
rev: ['production'], // rev the resulting bundle in prod
transforms: {
scripts: lazypipe().pipe(babel, {
presets: ['es2015']
}
)
}
}
My bundle task is:
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var bundle = require('gulp-bundle-assets');
var del = require('del');
[...]
gulp.task('bundle', function() {
del([
'./atlas3src/public/assets/bundles/**/*',
]);
return gulp.src('./bundle.config.js')
.pipe(bundle())
.pipe(bundle.results({
dest: './atlas3src/public/assets/',
pathPrefix: '/assets/bundles/'
}))
.pipe(gulp.dest('./atlas3src/public/assets/bundles/'));
});
And when i try to bundle it throws following error:
[20:30:33] Error in plugin "gulp-babel"
Message:
Plugin/Preset files are not allowed to export objects, only functions. In /home/ubuntu/workspace/node_modules/babel-preset-es2015/lib/index.js

I solved it myself. The problem was that I had multuple node_modules folders and gulp used the one with the false babel version.

Related

Browserify - ParseError: 'import' and 'export' may appear only with 'sourceType: module

In my gulpfile I have
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');
var babel = require("gulp-babel");
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var browserify = require('gulp-browserify');
var notify = require("gulp-notify");
gulp.task('js', function () {
gulp.src('js/main.js')
.pipe(babel())
.pipe(browserify())
.on('error', errorAlert)
.pipe(rename('./dist/js/bundle.js'))
//.pipe(uglify())
.pipe(gulp.dest('./'))
.pipe(notify({title: "Success", message: "Well Done!", sound: "Glass"}));
})
and in my app.js I am trying to import but get the errror
import SimpleBreakpoints from 'simple-breakpoints'
Any idea how to get rid of the error and use the import syntax?
Edit: the .babelrc
{
"presets": ["es2015"],
}
In your configuration, you pipe js/main.js to Babel, so that's the only file that will be transpiled. When Browserify requires app.js, it will seen ES6 content and will effect the error you are seeing.
You could use Babelify to solve the problem. It's a Browserify transform that will transpile the source that Browserify receives.
To install it, run this command:
npm install babelify --save-dev
And to configure it, change your task to:
gulp.task('js', function () {
gulp.src('js/main.js')
.pipe(browserify({ transform: ['babelify'] }))
.on('error', errorAlert)
.pipe(rename('./dist/js/bundle.js'))
//.pipe(uglify())
.pipe(gulp.dest('./'))
.pipe(notify({ title: "Success", message: "Well Done!", sound: "Glass" }));
})
Browserify in Gulp
For those who work with gulp and want to transpile ES6 to ES5 with browserify, you might stumble upon gulp-browserify plug-in. Warning as it is from version 0.5.1 gulp-browserify is no longer suported!!!. Consequences, of this action and transpiling with gulp-browserify will result with source code that might produce errors such as the one in question or similar to these: Uncaught ReferenceError: require is not defined or Uncaught SyntaxError: Unexpected identifier next to your import statements e.g. import * from './modules/bar.es6.js';
Solution
Althoutg gulp-browserify recomends to "checkout the recipes by gulp team for reference on using browserify with gulp". I found this advice to no avail. As it is now (2st July 2019) solution that worked for me was to replace gulp-browserify with gulp-bro#1.0.3 plug-in. This successfully, transpired ES6 to ES5 (as it is now) - It might change in future since support for JavaSript libraries decays with time of it appearance.
Assumption: To reproduce this solution you should have installed docker. Beside that you should be familiar with babel and babelify.
Source Code
This solution was successfully reproduced in docker environment, run node:11.7.0-alpine image.
Project Structure
/src <- directory
/src/app/foo.es6.js
/src/app/modules/bar.es6.js
/src/app/dist <- directory
/src/app/dist/app.es5.js
/src/gulpfile.js
/src/.babelrc
/src/package.json
/src/node_modules <- directory
Step 1: Run docker image
$ docker run --rm -it --name bro_demo node:11.7.0-alpine ash
Step 2: Create directories and source files
$ mkdir -p /src/dist
$ mkdir -p /src/app/modules/
$ touch /src/app/foo.es6.js
$ touch /src/app/modules/bar.es6.js
$ touch /src/gulpfile.js
$ touch /src/.babelrc
$ touch /src/package.json
$ cd /src/
$ apk add vim
.babelrc
{
"presets": ["#babel/preset-env"]
}
package.json
{
"name": "src",
"version": "1.0.0",
"description": "",
"main": "",
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"babelify": "^10.0.0",
"gulp": "^4.0.2",
"gulp-bro": "^1.0.3",
"gulp-rename": "^1.2.2"
}
}
bar.es6.js
"use strict"
class Bar {
constructor(grammar) {
console.log('Bar time!');
}
}
export default Bar;
foo.es6.js
"use strict"
import Bar from './modules/bar.es6.js';
class Foo {
constructor(grammar) {
console.log('Foo time!');
}
}
var foo = new Foo()
var bar = new Bar()
gulpfile.js
const bro = require('gulp-bro');
const gulp = require('gulp');
const rename = require('gulp-rename');
const babelify = require('babelify');
function transpileResources(callback) {
gulp.src(['./app/foo.es6.js'])
.pipe(bro({transform: [babelify.configure({ presets: ['#babel/preset-env'] })] }))
.pipe(rename('app.es5.js'))
.pipe(gulp.dest('./dist/'));
callback();
}
exports.transpile = transpileResources;
Step 3 - Transpile ES6 to ES5
$ npm install
$ npm install -g gulp#4.0.2
$ gulp transpile
[09:30:30] Using gulpfile /src/gulpfile.js
[09:30:30] Starting 'transpile'...
[09:30:30] Finished 'transpile' after 9.33 ms
$ node dist/app.es5.js
Foo time!
Bar time!
Source code after transpilation app.es5.js
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
var _barEs = _interopRequireDefault(require("./modules/bar.es6.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Foo = function Foo(grammar) {
_classCallCheck(this, Foo);
console.log('Foo time!');
};
var foo = new Foo();
var bar = new _barEs["default"]();
},{"./modules/bar.es6.js":2}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Bar = function Bar(grammar) {
_classCallCheck(this, Bar);
console.log('Bar time!');
};
var _default = Bar;
exports["default"] = _default;
},{}]},{},[1]);
Simply switching to webpack instead of browserify fixed the issue for me.
var webpack = require('webpack-stream')
gulp.task('default', function () {
return gulp.src('src/source.js')
.pipe(webpack({
output: {
filename: 'app.js'
}
}))
.pipe(gulp.dest('dist/app.js'))
})

Setting Up Gulp - Cannot find module 'gulp'

I am new to Gulp and am following a tutorial. I get to the final step and run gulp in my project file but I receive an error saying that the module 'gulp' cannot be found. I have verified that I have installed gulp. Both CLI (on a side note, what does CLI mean?) and Local versions are 3.9.1. I am wondering what am I doing incorrectly?
gulpfile.js:
// Include gulp
var gulp = require('gulp');
// Include Our Plugins
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
// Lint Task
gulp.task('lint', function() {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// Concatenate & Minify JS
gulp.task('scripts', function() {
return gulp.src('js/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('all.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
// Watch Files For Changes
gulp.task('watch', function() {
gulp.watch('js/*.js', ['lint', 'scripts']);
});
// Default Task
gulp.task('default', ['lint', 'scripts', 'watch']);
package.json:
{
"name": "gulp",
"version": "3.9.1",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"gulp-concat": "^2.6.0",
"gulp-jshint": "^2.0.1",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^1.5.4",
"jshint": "^2.9.2"
}
}
file structure:
|-- gulpfile.js
|-- package.json
|-- node_modules
| |-- .bin
| |-- gulp-concat
| |-- gulp-jshint
| |-- gulp-rename
| |-- gulp-uglify
| |-- jshint
error:
Issue is because my project folder is named 'gulp'. Changing the project folder to anything else other than 'gulp' solved the issue. https://github.com/npm/npm/issues/11772
Install Gulp in your devDependencies
npm install --save-dev gulp
Go to Your DIrectory , which is
D:\xampp\htdocs\test\gulp>npm install --save-dev gulp
And Hit Enter

Gulp tasks defined into a dependency module are not reachable

I have tasks I would like to share across several projects, so I moved them inside another module, which I load from my target project's gulpfile.js.
Project A tree:
gulpfile.js
package.json
...
gulpfile.js:
require('my-gulp-tasks')({
version: '0.0.1',
production: utils.env.production,
port: ...
// misc settings to customize tasks
});
My gulp tasks module tree:
index.js
tasks/
clean.js
assets.js
...
index.js (simplified version):
var gulp = require('gulp');
module.exports = function (settings) {
//...
gulp.task('clean', require('./tasks/clean')(settings));
return gulp;
}
But when I ask for the known tasks from within "Project A" with gulp -T, the command's output is empty...
What am I missing?
I finally got it working by passing a gulp instance from the gulpfile to the module, and avoiding to require gulp locally.
I ended up with:
Project A:
gulpfile.js:
var gulp = require('gulp');
require('my-gulp-tasks')(gulp, {
// settings...
});
My gulp tasks module:
index.js:
module.exports = function (gulp, settings) {
//...
gulp.task('clean', require('./tasks/clean')(settings));
return gulp;
}
clean.js:
var rm = require('gulp-rm');
module.exports = function (gulp) {
return function () {
return gulp.src('dist/**/*').pipe(rm());
};
};

Is there a way to use browserify-shim without package.json?

I need to use browserify-shim for some of my browserify dependencies, but I can't edit my package.json. I'm using browserify inside of gulp. It is possible to specify all of the package.json portion exclusibely form the API? I'm envisioning something like this:
return gulp.src('glob/path/to/my/main/js/file.js')
.pipe(browserify({
debug: false,
transform: ['browserify-shim'],
shim: {
'jquery': {
exports: 'jQuery'
}
}
}));
Then, my output with repalce var $ = require('jquery'); with var $ = jQuery;, since we are now utilizing jQuery as a global. Is this possible? Whne
You could use exposify transform in that case. browserify-shim is actially based on it and is written by the same guy.
E.g.:
return browserify('glob/path/to/my/main/js/file.js', { debug: false })
.transform('exposify', { expose: {'jquery': 'jQuery' }})
gulpfile.js
gulp = require('gulp')
browserify = require('gulp-browserify')
gulp.task('browserify', function(){
var src = 'test.js'
gulp.src(src)
.pipe(browserify({
shim: {
jQuery: {
path: './bowser_components/jquery/dist/jquery.min.js',
exports: '$'
}
}
}))
.pipe(gulp.dest('./build/js'))
})
test.js
$ = require('jQuery')
console.log($);

Gulp to combine bower files

I'm aware this has probably been asked before, but I can't seem to be able to ask Google the right questions to find what I need. So I'm possibly thinking about this in the wrong way.
Basically, I need to know if there is a way to use Gulp with Bower so that all css files in subdirectories under bower_components are combined into one styles.css, all js files in subdirectories under bower_components are combined into one scripts.js. Kind of how assetic works in symfony2 to combine assets into single files. Does each 'built' file in each bower_componets subdirectory have to be linked to manually (in the Gulp config file), or is it more common to loop through them programatically?
Thanks
Would something like the below help? It loops through all css files in my 'src' directory and spits out one css file in the 'dist' folder. It does the same for my js files:
// Config
var requireJsRuntimeConfig = vm.runInNewContext(fs.readFileSync('src/app/require.config.js') + '; require;');
requireJsOptimizerConfig = merge(requireJsRuntimeConfig, {
out: 'scripts.js',
baseUrl: './src',
name: 'app/startup',
paths: {
requireLib: 'bower_modules/requirejs/require'
},
include: [
'requireLib',
'components/nav-bar/nav-bar',
'components/home-page/home',
'text!components/about-page/about.html'
],
insertRequire: ['app/startup'],
bundles: {
// If you want parts of the site to load on demand, remove them from the 'include' list
// above, and group them into bundles here.
// 'bundle-name': [ 'some/module', 'another/module' ],
// 'another-bundle-name': [ 'yet-another-module' ]
}
});
// Discovers all AMD dependencies, concatenates together all required .js files, minifies them
gulp.task('js', function () {
return rjs(requireJsOptimizerConfig)
.pipe(uglify({ preserveComments: 'some' }))
.pipe(gulp.dest('./dist/'));
});
// Concatenates CSS files, rewrites relative paths to Bootstrap fonts, copies Bootstrap fonts
gulp.task('css', function () {
var bowerCss = gulp.src('src/bower_modules/components-bootstrap/css/bootstrap.min.css')
.pipe(replace(/url\((')?\.\.\/fonts\//g, 'url($1fonts/')),
appCss = gulp.src('src/css/*.css'),
combinedCss = es.concat(bowerCss, appCss).pipe(concat('css.css')),
fontFiles = gulp.src('./src/bower_modules/components-bootstrap/fonts/*', { base: './src/bower_modules/components-bootstrap/' });
return es.concat(combinedCss, fontFiles)
.pipe(gulp.dest('./dist/'));
});
there is a way and its honestly really simple. you can install "gulp-run" to your npm devDependencies and then use the run to execute bower install.
var gulp = require('gulp'),
del = require('del'),
run = require('gulp-run'),
sass = require('gulp-sass'),
cssmin = require('gulp-minify-css'),
browserify = require('browserify'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
jshint = require('gulp-jshint'),
browserSync = require('browser-sync'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
reactify = require('reactify'),
package = require('./package.json'),
reload = browserSync.reload;
/**
* Running Bower
*/
gulp.task('bower', function() {
run('bower install').exec();
})
/**
* Cleaning lib/ folder
*/
.task('clean', function(cb) {
del(['lib/**'], cb);
})
/**
* Running livereload server
*/
.task('server', function() {
browserSync({
server: {
baseDir: './'
}
});
})
/**
* sass compilation
*/
.task('sass', function() {
return gulp.src(package.paths.sass)
.pipe(sass())
.pipe(concat(package.dest.style))
.pipe(gulp.dest(package.dest.lib));
})
.task('sass:min', function() {
return gulp.src(package.paths.sass)
.pipe(sass())
.pipe(concat(package.dest.style))
.pipe(cssmin())
.pipe(gulp.dest(package.dest.lib));
})
/**
* JSLint/JSHint validation
*/
.task('lint', function() {
return gulp.src(package.paths.js)
.pipe(jshint())
.pipe(jshint.reporter('default'));
})
/** JavaScript compilation */
.task('js', function() {
return browserify(package.paths.app)
.transform(reactify)
.bundle()
.pipe(source(package.dest.app))
.pipe(gulp.dest(package.dest.lib));
})
.task('js:min', function() {
return browserify(package.paths.app)
.transform(reactify)
.bundle()
.pipe(source(package.dest.app))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(package.dest.lib));
})
/**
* Compiling resources and serving application
*/
.task('serve', ['bower', 'clean', 'lint', 'sass', 'js', 'server'], function() {
return gulp.watch([
package.paths.js, package.paths.jsx, package.paths.html, package.paths.sass
], [
'lint', 'sass', 'js', browserSync.reload
]);
})
.task('serve:minified', ['bower', 'clean', 'lint', 'sass:min', 'js:min', 'server'], function() {
return gulp.watch([
package.paths.js, package.paths.jsx, package.paths.html, package.paths.sass
], [
'lint', 'sass:min', 'js:min', browserSync.reload
]);
});
what is really beautiful with this setup I just posted is this is making a custom gulp run called "serve" that will run your setup with a development server (with live reload and much better error intelligence) all you have to do is go to your directory and type "gulp serve" and it'll run bower install and build everything for you. obviously the folder structure is different so you will need to make some modifications, but hopefully this shows how you can run bower with gulp :)
Something like the below was what I was looking for, except I don't like having to add the paths manually. This is why I prefer something like CommonJS for Javascript. I definitely remember seeing a way in which CSS files were picked up automatically from the bower_components folder, I believe it was in the Wordpress Roots project (based on the settings/overrides in bower.json).
gulp.task('css', function () {
var files = [
'./public/bower_components/angular-loading-bar/build/loading-bar.css',
'./public/bower_components/fontawesome/css/font-awesome.css'
];
return gulp.src(files, { 'base': 'public/bower_components' })
.pipe(concat('lib.css'))
.pipe(minifyCss())
.pipe(gulp.dest('./public/build/css/')
);
});
gulp.task('js-lib', function () {
var files = [
'public/bower_components/jquery/dist/jquery.js',
'public/bower_components/bootstrap-sass/assets/javascripts/bootstrap.js'
];
return gulp.src(files, { 'base': 'public/bower_components/' })
.pipe(sourcemaps.init())
.pipe(uglify({ mangle: false }))
.pipe(concat('lib.js'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/build/js/')
);
});
You can use gulp-main-bower-files library to add the main files of packages in .bower.json instead to declare them manually