Can't define Node_ENV in Webpack - configuration

I am trying to use webpack but have this issue with the ENV when using feathers-configuration pack:
Uncaught TypeError: Cannot read property 'getEnv' of undefined
at Function.<anonymous> (vendor.npm.js:37275)
at Function.configure (vendor.npm.js:27533)
at Object.59 (index.js:38)
at __webpack_require__ (manifest.js:51)
at Object.0 (index.js:8)
at __webpack_require__ (manifest.js:51)
at webpackJsonpCallback (manifest.js:22)
at index.js:1
The error in the vendor.npm.js package is. Feathers-configuration is using the config.getEnv method and can't find NODE_ENV.
var env = config.util.getEnv('NODE_ENV');
I am even trying to use the defineplugin but it doesn't work:
new webpack.DefinePlugin({
DEBUG: true,
"process.env":{
"NODE_ENV": JSON.stringify("production")
}
}),

try to use below plugin https://www.npmjs.com/package/extended-define-webpack-plugin
// webpack.config.js
var ExtendedDefinePlugin = require('extended-define-webpack-plugin');
var appConfig = require('./app.config.js');
module.exports = {
// ...
plugins: [
/* ..., */
new ExtendedDefinePlugin({
APP_CONFIG: appConfig,
})
]
};

Related

Using requireJS with svgPanZoom giving error: Uncaught TypeError: svgPanZoom is not a function

I have been using svg-pan-zoom library successfully with my javascript app but I now need to refactor it to use requireJS.
My util.js is:
define([
'baja!',
'jquery',
'/file/WebWidgets/js/libraries/svg-pan-zoom.js'
], function (
baja,
$,
svgPanZoom) {
'use strict';
const updateInitializeDiv = () => {
const svgDocument = $('#svgObjectElementFromBinding')[0].contentDocument;
const svgDocumentElement = svgDocument.documentElement;
console.log(svgDocumentElement);
console.log(svgDocumentElement.tagName);//svg
let panZoomSVG = svgPanZoom(svgDocumentElement, {
zoomEnabled: true,
controlIconsEnabled: true
});
}
const util = {};
util.updateInitializeDiv = updateInitializeDiv;
return util;
});
I am getting "Uncaught TypeError: svgPanZoom is not a function".
Can anyone suggest what I am doing wrong?
I had to reference the svg-pan-zoom library in the RequireJS config to get this to work.

GulpUglifyError: unable to minify JavaScript error with Browserify

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.

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

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.

Trying to use request with ES6 + Webpack, but I am getting an error

I am currently trying to create a webapp with React, and I am trying to make a request to my server (with request). However, whenever I try to webpack the app I get an error. I am almost certain it has to do with request having to be labeled as an external library, but I can't get it to work. Can anybody help me?
Here is my webpack config.
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin();
module.exports = {
entry : [
'./js/index.js'
],
output : {
path : __dirname + '/lib/',
publicPath : 'http://localhost:8080',
filename : 'bundle.js'
},
plugins : [
new ExtractTextPlugin('app.css'),
new webpack.NoErrorsPlugin()
],
module : {
loaders : [
{
test : /\.js$/,
loaders : [
'babel'
],
exclude : /node_modules/
},
{
test : /\.(jpe?g|png|gif|svg)$/i,
loaders : [
'url?limit=8192',
'img'
]
},
{
test : /\.scss$/,
include : /styles/,
loader : extractCSS.extract([
'css',
'autoprefixer',
'sass'
])
}
]
},
resolve : {
extensions : ['', '.js', '.json']
},
externals : {
request : 'request'
}
};
and here is the error that I am getting
ERROR in ./js/services/comic
Module parse failed: /Users/matthew.pfister/IdeaProjects/web/js/services/comic Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import request from 'request';
|
| export default {
# ./js/creators/comic.js 11:21-49
Here is the file it is referencing
import request from 'request';
export default {
...
};
I dont think export default {...} is valid. try
var o = {...}
export default o
should work.
I just realized that the file that is throwing the error doesn't have the .js extension.
::facepalm:: everything is fixed.