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

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'))
})

Related

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

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.

Transpile ES6 import/export with babel 6 and gulp

I would like to use ES6 import / export. I use Gulp 3.9 with babel.js 6.
I want to import functions.js into form.js.
I get the following error:
ReferenceError: require is not defined
== MY SETUP ==
functions.js
var helper = {
insertAfter: function(el, elParent) {
elParent.parentNode.insertBefore(el, elParent.nextSibling);
},
resetTextfield: function(el) {
let reinitTextfield = new mdc.textField.MDCTextField(el);
let label = el.firstElementChild.nextElementSibling;
label.classList.remove('mdc-text-field__label--float-above');
reinitTextfield.value = '';
}
}
// Export
export default helper;
form.js
// Import functions.js
import helper from './functions.js';
My Gulp task:
// babel js task - transpile our Javascript into the build directory
gulp.task("js-babel", () => {
$.fancyLog("-> Transpiling Javascript via Babel...");
return gulp.src(pkg.globs.babelJs)
.pipe($.plumber({errorHandler: onError}))
.pipe($.newer({dest: pkg.paths.build.js}))
.pipe($.babel())
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.build.js));
});
.babelrc:
{
"presets": ["es2015"],
"compact": true
}
I thought babel.js transpiles the JS and I can use import / export.
Now, am I reading that I need Browserify with Babelify ?!
Will that replace my "js-babel" task?
How should I rebuild my task?

gulp-image-optimization build gives error

My Node and Npm Vesrions are below
node v6.9.1
npm v3.10.9
My code is
'use strict';
const gulp = require('gulp');
const imageop = require('gulp-image-optimization');
let dir = {
srcImages: 'public/wps/source/images',
build: 'public/wps/build/'
};
const config = {
src: dir.srcImages + '/**/*',
dest: dir.build + 'images/'
};
gulp.task('img-prod', function (cb) {
gulp.src(config.src).pipe(imageop({
optimizationLevel: 5,
progressive: true,
interlaced: true
})).pipe(gulp.dest(config.dest)).on('end', cb).on('error', cb);
});
When i do gulp build it throws an error
internal/child_process.js:289
var err = this._handle.spawn(options);
^
TypeError: Bad argument
at TypeError (native)
at ChildProcess.spawn (internal/child_process.js:289:26)
at exports.spawn (child_process.js:380:9)
at Imagemin._optimizeJpeg (/Users/sureshraju/xxx/Wps/web-pres/node_modules/image-min/imagemin.js:126:12)
at Imagemin.optimize (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:57:26)
at module.exports (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:179:21)
at /Users/sureshraju/xxxx/Wps/web-pres/node_modules/gulp-image-optimization/index.js:38:17
at FSReqWrap.oncomplete (fs.js:123:15)
Do you have svg files in your source directory?
I have just been getting the exact same problem in a project I have picked up from someone else.
I omitted svg files from the glob and the task then ran without errors.

Aurelia bundle all jspm dependencies automatically

I'm trying to automatically bundle all jspm dependencies --so I don't have to maintain a manual list-- with a gulp task:
var gulp = require('gulp');
var bundler = require('aurelia-bundler');
var package = require('../../package.json');
var jspmDeps = Object.keys(package.jspm.dependencies);
var config = {
force: true,
baseURL: '.',
configPath: './system.config.js',
bundles: {
"output/jspm": {
"includes": jspmDeps,
"options": {
"minify": false,
"inject" : true
}
}
}
};
gulp.task('build-jspm', function () {
return bundler.bundle(config);
});
Unfortunately, this isn't picking up and bundling all sub-dependencies of the modules included in the bundle. Quite a few dependencies are dynamically loaded by aurelia, which don't get detected during bundling.
Is there a way to force aurelia-bundler (or jspm-cli) to bundle the entire dependency tree from jspm?
[Update] Turns out jspm's bundler has the same behavior, in that it won't bundle modules unless it detects a call to import 'some-sub-dependency'; there are plans to trace dynamic loading at some point

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