ResumableJs not working with Webpack / Webpackencore - javascript

I have installed Resumablejs with Yarn and I see it in node_module folder.
Webpack.config.js
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or sub-directory deploy
//.setManifestKeyPrefix('build/')
/*
* ENTRY CONFIG
*
* Add 1 entry for each "page" of your app
* (including one that's included on every page - e.g. "app")
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
.addEntry('app', './assets/js/app.js')
....
var config = Encore.getWebpackConfig();
var path = require('path');
config.resolve.alias = {
'jquery': path.resolve(__dirname, 'node_modules/jquery/src/jquery'),
'resumablejs': path.resolve(__dirname, 'node_modules/resumablejs/resumable')
};
module.exports = config;
package.json
"dependencies": {
...
"resumablejs": "^1.1.0",
...
}
app.js
/*
* Welcome to your app's main JavaScript file!
*
* We recommend including the built version of this JavaScript file
* (and its CSS file) in your base layout (base.html.twig).
*/
// any CSS you require will output into a single css file (app.css in this case)
require('../css/app.scss');
const $ = require('jquery');
global.$ = global.jQuery = $;
require('resumablejs');
...
import './EntriesJs';
EntriesJs
import AppScripts from './js/appScripts';
export {
AppScripts
}
In my app.js i have declare it require('resumablejs'); and then in my file I want to use it like this:
module.exports = function (uploadJs) {
return filesUploadScript();
};
function filesUploadScript() {
(function () {
console.log('js loaded...');
var uploaderWidgetProperties = $('#_f-uploader-widget-properties');
var r = new Resumable({ ... });
but at this point I am getting the following error:
Uncaught ReferenceError: Resumable is not defined
I have a hard time understanding Webpack so any help will be great.

Related

Uncaught ReferenceError: {Class} is not defined

Sorry if this question has already been answered, but there are so many post with this error name and a different context, that I could find the answer to this particular case.
I am using Javascript ES6 modules, and I am trying to 'compile' all my javascript files into one minified file. I am using Gulp for that. I have 3 js files (gulpfiles, an index file that require ma class, and the class file). I also have an HTML file to test the minified js file. Here is what my project looks like :
// File : gulpfile.js
const { src, dest, task, watch, series, parallel } = require('gulp');
var uglify = require('gulp-uglify')
var babelify = require('babelify')
var browserify = require('browserify')
var source = require('vinyl-source-stream')
var buffer = require('vinyl-buffer')
var rename = require('gulp-rename')
const jsSRC = './classes/'
const jsDEST = './output/'
const jsFILES = ['index.js']
function js(done) {
jsFILES.map( function (entry) {
return browserify({
entries: [jsSRC + entry]
})
.transform( babelify, { presets: ['#babel/preset-env'] } )
.bundle()
.pipe( source( entry) )
.pipe( rename({ extname: '.min.js'}) )
.pipe( buffer() )
.pipe( uglify() )
.pipe( dest( jsDEST ))
})
done()
}
task('js',js)
task('default', parallel(js))
// File : classes/Logger.js
class Logger{
constructor(msg){
console.log(msg)
}
}
export default Logger ;
// File : classes/index.js
import Logger from './Logger.js'
exports = { Logger }
var l = new Logger('Hello') // This should log 'Hello' in the console
// File : demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Demo</title>
</head>
<body>
<script src="./output/index.min.js"></script>
</body>
</html>
(I used the command npm install #babel/core #babel/preset-env babelify browserify gulp gulp-cli gulp-rename gulp-uglify vinyl-buffer vinyl-source-stream to install all the dependecies)
So, here is the problem. When I open the HTML file in a browser, I get the 'Hello' displayed in the console, because it is triggered by the var l = new Logger('Hello') line in the index.js file. But if I type the exact same thing in the console, I get this error Uncaught ReferenceError: Logger is not defined
This is probably a noob mistake. Do someone knows why I cannot use the Logger class from my page with the minified js ? And what can I do to make my class usable from the minified js file ?
Thank you !
(If there is a problem with the question, duplicated question or whatever, just tell me and I will close/delete it)

How to fix a Gulp generated file being too large

I am trying to use Gulp to generate a file,
gulphile.js
const elixir = require('laravel-elixir');
require('laravel-elixir-vue-2');
elixir(mix => {
mix.sass('app.scss')
.webpack('app.js');
});
app.js
window._ = require('lodash');
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
window.Vue = require('vue');
require('vue-resource');
When I run the command gulp watch Gulp generates a file with a very big size (about 3mb), and the file does not look like it is minimized.
It looks something like this:
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 11);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {
eval("var g;\r\n\r\n// This works in non-strict
mode\r\ng = (function() { return this; })();\r\n\r\ntry {\r\n\t// This
works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")
() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window refer
How can I fix it to generate the file correctly minimized?
Use the --production option to run the tasks to minimize the css and js files.
gulp --production
This option works with watch, as well:
gulp watch --production

Gulp - minify without creating random string

I use "gulp build" to generate a single .js file from a set of .js files (angular code).
It is creating file like "app-randomstring.js" but I want it to be "app.js", how to do that ?
gulpfile.js:
/**
* Welcome to your gulpfile!
* The gulp tasks are splitted in several files in the gulp directory
* because putting all here was really too long
*/
'use strict';
var gulp = require('gulp');
var wrench = require('wrench');
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
wrench.readdirSyncRecursive('./gulp').filter(function(file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
I use something like this:
var concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
gulp.task('build-js', [], function () {
jslibs = ['path/to/file.js', 'path/to/file2.js'];
return gulp.src(jslibs)
.pipe(concat('all.min.js')) // the name you want
.pipe(uglify({mangle: false}))
.pipe(gulp.dest('output/path/js/'))
});

package files by folder with gulp

I want this:
|-- guides
| |-- _guide.hbs
| |-- guide.hbs
| `-- index.hbs
|-- index.hbs
`-- noroute.hbs
turn into this:
|-- common.js
`-- guides.js
As you can see guides folder squashed into guides.js, and . folder squashed into common.js
Below is my ugly solution.
Inspired by this post
function getFolderMap(dir) {
var fs = require('fs');
var path = require('path');
var result = {};
fs.readdirSync(dir)
.filter(function(file) {
if( fs.statSync(path.join(dir, file)).isDirectory()) {
result[file] = file;
}
});
return result;
};
gulp.task('build-dev-templates3', function() {
var mergeStream = require('merge-stream')();
var templatePaths = getFolderMap(paths.src + '/templates');
templatePaths['./'] = 'common';
for (var src in templatePaths) {
var dst = templatePaths[src];
var stream = gulp.src([paths.src + '/templates/' + src + '**/*.hbs'])
.pipe($.process())
.pipe($.concat(dst + '.js'))
.pipe(gulp.dest(paths.dest + '/templates'));
mergeStream.add(stream);
}
return mergeStream;
});
What is the gulp way to achieve this? Please at least share some guideful tools.
Edit2
I need to get rid of getFolderMap function and solve this with pure
streams. The closest i can get is:
var directoryFilter = $.filter(function (file) {
return file.isDirectory();
});
gulp.src([paths.src + + '/templates/**'])
.pipe(directoryFilter)
.pipe(
//here I have list of directories
//I need a gulp plugin to get the contents
// so i can process them.
);
This issue is related https://github.com/gulpjs/gulp/issues/386.
Final Solution
This is my final solution based on spiralx's answer.
https://gist.github.com/eguneys/2fdbe7ac83dfab04748a
Something like this is my first guess, I use the forEachModule function at work to execute a sub-task for every module and then combine the results - helps with some plugins that have issues with paths and includes (gulp-stylus IIRC):
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var es = require('event-stream');
var path = require('path');
var config = require('./build.config');
// ------------------------------------
/*
* For each module execute subtaskFunc and get result stream, then
* combine all of the streams and return that.
*
* #param [{Object}] modules array of module objects
* #param {Function} subtaskFunc function(module) -> stream
* #return {Object} a stream
*/
function forEachModule(modules, subtaskFunc) {
var subtaskStreams = modules.map(subtaskFunc);
return es.concat.apply(null, subtaskStreams);
}
// ------------------------------------
gulp.task('templates', function() {
var dest = path.join(config.dest, 'templates');
return forEachModule(config.modules, function(module) {
var src = path.join(config.src, 'templates', module, '**/*.hbs');
// Compile .hbs files, wrap in a CommonJS module, combine into `<module>.js` and write to dest.
return gulp.src(src)
.pipe(plugins.handlebars().on('error', plugins.util.log))
.pipe(plugins.defineModule('plain'))
.pipe(plugins.declare({
namespace: 'app.templates.' + module
}))
.pipe(plugins.concat(module + '.js'))
.pipe(gulp.dest(dest));
})
// Combine all module template files into one?
.pipe(plugins.concat('templates.js'))
.pipe(gulp.dest(config.dest));
});
Edit:
This code is almost identical to what was there, but looks for directories under 'src/app' for modules instead of pre-defining the list, and doesn't generate any configuration outside of the gulp task function itself.
The reason it's like this to begin with was issues using gulp-stylus on a stream such as src/app/**/*.styl when a) using #include or anything referring to relative paths, or b) passing options to either Stylus itself, or a plugin such as Nib.
var modules = fs.readdirSync('src/app').filter(function(name) {
return fs.statSync('src/app/' + name).isDirectory()
});
// ------------------------------------
gulp.task('styles', function() {
var streams = modules.map(function(name) {
return gulp.src('src/app/' + name + '/**/*.styl')
.pipe(plugins.stylus({
use: [
require('nib')(),
require('bootstrap3-stylus')()
],
paths: [
'src/common'
]
}))
.pipe(plugins.concat(name + '.css'))
.pipe(gulp.dest('dist/css'))
.pipe(plugins.minifyCss())
.pipe(plugins.rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/css'));
});
return plugins.mergeStream(streams)
.pipe(plugins.concat('app.css'))
.pipe(gulp.dest('dist/css'));
});

How to perform a transform on npm module using browserify

By default, browserify does not perform transforms on modules included from node_modules, i.e. with no path.
I made a quick github repo that illustrates it here. The index.js file that gets browserified looks like this:
var fs = require('fs');
var testmodule = require('testmodule');
var trg1 = document.getElementById("target1");
var trg2 = document.getElementById("target2");
trg1.innerHTML = fs.readFileSync(__dirname+"/something.txt");
trg2.innerHTML = testmodule();
testmodule looks like this:
var fs = require('fs');
exports = module.exports = function() {
return fs.readFileSync(__dirname+'/data.txt');
}
Using the brfs transform module, I want to be able to inline both calls to fs.readFileSync, but when I run browserify index.js -t brfs -o bundle.js, only the call in my main project gets inlined. Here is the bundle.js result:
;(function(e,t,n){function r(n,i){if(!t[n]){if(!e[n]){var s=typeof require=="function"&&require;if(!i&&s)return s(n,!0);throw new Error("Cannot find module '"+n+"'")}var o=t[n]={exports:{}};e[n][0](function(t){var i=e[n][1][t];return r(i?i:t)},o,o.exports)}return t[n].exports}for(var i=0;i<n.length;i++)r(n[i]);return r})({1:[function(require,module,exports){
// nothing to see here... no file methods for the browser
},{}],2:[function(require,module,exports){
var fs = require('fs');
var testmodule = require('testmodule');
var trg1 = document.getElementById("target1");
var trg2 = document.getElementById("target2");
trg1.innerHTML = "This is data from a file in the main project folder"; // TRANSFORMED
trg2.innerHTML = testmodule();
},{"fs":1,"testmodule":3}],3:[function(require,module,exports){
(function(__dirname){var fs = require('fs');
exports = module.exports = function() {
return fs.readFileSync(__dirname+'/data.txt'); // NO TRANSFORM
}
})("/node_modules/testmodule")
},{"fs":1}]},{},[2])
;
Got some help from substack (author of browserify) on this one. To specify if a module outside of a project requires transformations, you need to specify a browserify.transform array in your package.json. So for the example I gave above, the package.json file in the testmodule directory looks like this:
{
"name":"testmodule",
"version":"0.0.0",
"browserify": {
"transform": ["brfs"]
},
"main": "index.js"
}
You can also use browserify -g brfs instead of browserify -t brfs. g is a global transform (which applies to dependencies)

Categories

Resources