I'm bundling my script with Browserify + Babel like this:
function buildJs() {
let bopts = {
paths: [
`${SRC}/js`,
'./config'
],
debug: !isProduction
};
let opts = Object.assign({}, watchify.args, bopts);
let b = watchify(persistify(opts));
b.add(`${SRC}/js/index.js`)
.on('update', bundle)
.on('log', gutil.log)
.external(vendors)
.transform(babelify, {
presets: ["es2015", "react"],
plugins: [
"syntax-async-functions",
"transform-regenerator",
"transform-class-properties",
"transform-decorators-legacy",
"transform-object-rest-spread",
"transform-react-jsx-source",
staticFs
]
})
.transform(browserifyCss, { global: true });
function bundle() {
let stream = b.bundle()
.on('error', swallowError)
.on('end', () => {
gutil.log(`Building JS:bundle done.`);
})
.pipe(source('bundle.js'))
.pipe(streamify(uglify()));
return stream.pipe(gulp.dest(`${DIST}/js`));
}
return bundle();
}
It's just browserify -> babelify -> browserify-css -> uglify -> gulp.dest.
But If I ran this task, it fails with:
[17:00:30] Using gulpfile ~/ctc-web/gulpfile.js
[17:00:30] Starting 'build'...
[17:00:46] 1368516 bytes written (16.43 seconds)
[17:00:46] Building JS:bundle done.
events.js:160
throw er; // Unhandled 'error' event
^
GulpUglifyError: unable to minify JavaScript
at createError (/home/devbfex/ctc-web/node_modules/gulp-uglify/lib/create-error.js:6:14)
at wrapper (/home/devbfex/ctc-web/node_modules/lodash/_createHybrid.js:87:15)
at trycatch (/home/devbfex/ctc-web/node_modules/gulp-uglify/minifier.js:26:12)
at DestroyableTransform.minify [as _transform] (/home/devbfex/ctc-web/node_modules/gulp-uglify/minifier.js:79:19)
at DestroyableTransform.Transform._read (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_transform.js:159:10)
at DestroyableTransform.Transform._write (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_transform.js:147:83)
at doWrite (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:338:64)
at writeOrBuffer (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:327:5)
at DestroyableTransform.Writable.write (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:264:11)
at Transform.ondata (_stream_readable.js:555:20)
Just skip uglify works, but I really need it.
The weird thing is that error was occured after end event. I tried using with vinyl-buffer, but same errors happen.
I couldn't find any solution, every my attemps fails with same error message.
What am I missing? Is there a something that I missed?
Try to replace let by var and see what happens.
Related
I have created a very complex build process for front-end of one web app, which is being tested on Appveyor. If some parts of the app are not being built correctly with gulp, if some gulp tasks fail, how do I signal the Appveyor that the build has failed in its entirety?
To solve this problem, I have used instructions from this article. I had a need to separate build process into two similar parts: one for development environment and another one for production environment. Main difference was that production environment should always break if error is found in some of the tasks. Feodor Fitsner suggested that process should exit with non-zero error code.
Combining these two solutions, I created this small JS module that should be used as a wrapper for gulp tasks:
const msg = require('bit-message-box')
const chalk = require('chalk')
module.exports = (taskFn, production = false) => function(done) {
let onSuccess = () => {
done()
}
let onError = (err) => {
if (production) {
// If build process is initiated in production env, it should always break
// on error with exit code higher than zero. This is especially important
// for Appveyor CI
msg.error(`ERROR! BUILD PROCESS ABORTED!`)
console.error(chalk.bgRed.white(err))
process.exit(1)
}
else { done() }
}
let outStream = taskFn(onSuccess, onError);
if (outStream && typeof outStream.on === 'function') {
outStream.on('end', onSuccess);
}
}
Then in gulp itself, you can import this module and use it in a following way:
const gulp = require('gulp')
const handleCI = require('./handleCI')
const sass = require('gulp-sass')
const PRODUCTION = true // use your own system to decide if this is true or false
gulp.task('styles', handleCI((success, error) => {
return gulp.src('./scss/style.scss')
.pipe(
sass()
.on('error', error) // Add this to handle errors
)
.pipe(
gulp.dest('./styles/')
.on('error', error)
)
}, PRODUCTION))
I'm trying to record puppeteer to see what happens when i run it on server, as I understand this package does what i want.
https://www.npmjs.com/package/puppeteer-recorder
so here is simplified version of my code
const puppeteer = require('puppeteer');
const { record } = require('puppeteer-recorder');
var path = 'C:\\wamp64\\www\\home_robot\\';
init_puppeteer();
const global_browser ;
async function init_puppeteer() {
global_browser = await puppeteer.launch({headless: false , args: ['--no-sandbox', '--disable-setuid-sandbox']});
check_login()
};
async function check_login()
{
try {
const page = await global_browser.newPage();
await page.setViewport({width: 1000, height: 1100});
await record({
browser: global_browser, // Optional: a puppeteer Browser instance,
page: page, // Optional: a puppeteer Page instance,
output: path + 'output.webm',
fps: 60,
frames: 60 * 5, // 5 seconds at 60 fps
prepare: function () {}, // <-- add this line
render: function () {} // <-- add this line
});
await page.goto('https://www.example.cob', {timeout: 60000})
.catch(function (error) {
throw new Error('TimeoutBrows');
});
await page.close();
}
catch (e) {
console.log(' LOGIN ERROR ---------------------');
console.log(e);
}
}
But I get this error
$ node home.js
(node:7376) UnhandledPromiseRejectionWarning: Error: spawn ffmpeg ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
at onErrorNT (internal/child_process.js:415:16)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:7376) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
id: 1)
(node:7376) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
LOGIN ERROR ---------------------
Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
at doWrite (_stream_writable.js:406:19)
at writeOrBuffer (_stream_writable.js:394:5)
at Socket.Writable.write (_stream_writable.js:294:11)
at Promise (C:\wamp64\www\home_robot\node_modules\puppeteer-recorder\index.j
s:72:12)
at new Promise (<anonymous>)
at write (C:\wamp64\www\home_robot\node_modules\puppeteer-recorder\index.js:
71:3)
at module.exports.record (C:\wamp64\www\home_robot\node_modules\puppeteer-re
corder\index.js:44:11)
at process._tickCallback (internal/process/next_tick.js:68:7)
i've even ran npm i reinstall ffmpeg --with-libvpx
as it was suggested here
https://github.com/clipisode/puppeteer-recorder/issues/6
but still didnt work .... wha telse do i need to do ?
I know this would be a very late response to your question, but nevertheless.
A years ago, I visited this same stack-overflow thread and I had similar challenge of finding a screen recorder library which does a good job a capturing the video as well as offers an options to manually start and stop the recording.
Finally I wrote one for myself and distributed as NPM library...!!
https://www.npmjs.com/package/puppeteer-screen-recorder
Hope this is helpful...!!
Add two empty functions called prepare and render in the options.
await record({
browser: global_browser, // Optional: a puppeteer Browser instance,
page, // Optional: a puppeteer Page instance,
output: path + 'output.webm',
fps: 60,
frames: 60 * 5, // 5 seconds at 60 fps,
prepare: function () {}, // <-- add this line
render: function () {} // <-- add this line
});
Basically it's missing some default functions and the error is not handled properly.
Also, there's https://www.npmjs.com/package/puppeteer-capture which uses HeadlessExperimental protocol.
I am trying to setup Stubby Server in my JavaScript environment and I am getting the error below.
The relevant part of my Gulpfile:
gulp.task('stubby', function(cb) {
var options = {
callback: function (server, options) {
server.get(1, function (err, endpoint) {
if (!err)
console.log(endpoint);
});
},
stubs: 8000,
tls: 8443,
admin: 8010,
files: [
'*.*'
]
};
stubby(options, cb);
});
The error:
[12:15:03] Starting 'stubby'...
[12:15:03] 'stubby' errored after 17 ms
[12:15:03] Error: Missing error message
at new PluginError (C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-util\lib\PluginError.js:73:28)
at readJSON (C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-stubby-server\index.js:90:15)
at C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-stubby-server\index.js:149:24
at Array.map (native)
at stubbyPlugin (C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-stubby-server\index.js:136:12)
at Gulp.<anonymous> (C:\Users\admin\IdeaProjects\myproject\gulpfile.js:54:5)
at module.exports (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\index.js:134:8)
Searching the gulp-stubby-server codebase for PluginError yields the follow snippet:
function readJSON(filepath, options) {
var src = fs.readFileSync(filepath, options),
result;
if (!options.mute) {
gutil.log(gutil.colors.yellow('Parsing ' + filepath + '...'));
}
try {
result = JSON.parse(src);
return result;
} catch (e) {
throw new gutil.PluginError(PLUGIN_NAME, 'Unable to parse "' + filepath + '" file (' + e.message + ').', e);
}
}
— Source on GitHub
You can tell this is the likely culprit because of the stack trace you see, where the PluginError is coming from readJSON.
The issue
Take note of the catch block. This is caused by one of the files matching your glob (*.*) not being a valid JSON file.
To fix
Ensure you are using the newest version of gulp-stubby-server
Ensure that you are using the correct glob (that is, do you really mean *.*)
Ensure that all the files in the current working directory are valid JSON files
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'))
})
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.