Browserify talking to another script - browserify

I want to use browserify, but I don't want to force users of library to do so. In other words, I want the generated bundle.js to define stuff that other scripts on the same page can find. I tried and failed with:
browserify -o bundle.js src/if.js
where:
::::::::::::::
index.html
::::::::::::::
<script src="bundle.js"></script>
<script>
function go() {
document.getElementById("victim").innerHTML=C();
}
</script>
<body onLoad="go();">
<div id='victim'>Foo</div>
</body>
::::::::::::::
src/if.js
::::::::::::::
var C = require("./c");
::::::::::::::
src/c.js
::::::::::::::
var A = require("./a");
var B = require("./b");
module.exports = function () { return A() + B(); };
::::::::::::::
src/a.js
::::::::::::::
module.exports = function () { return 10; };
::::::::::::::
src/b.js
::::::::::::::
module.exports = function () { return 20; };
This fails with "Reference error: C is not defined."
I don't mind forcing the author of the HTML and his scripts to type something strange, but I don't feel entitled to force him to include browseriy in his build process.
How do I do this?

Bingo! if.js should read
global.C = require("./c");

Related

How to copy a codepen.io example into a .vue

I found a codepen.io example (https://codepen.io/srees/pen/pgVLbm) I want to play around with in the context of a .vue app I'm working on, and I need some help transferring the <script> section over.
I copied the HTML chunk into a <template> and the CSS into a <style>. I've confirmed the .vue file works within the broader context (content loads when the <script> is commented out. I also placed <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" /> immediately before my <script> to resolve the $ not defined error I was getting. Is there something I need to import into App.vue or into this particular .vue file? When I leave <script> uncommented, I simply get a blank page loaded.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
<script>
var hidWidth;
var scrollBarWidths = 40;
...
you could define a method like this:
methods: {
renderStuff: function () {
var hidWidth;
var scrollBarWidths = 40;
var widthOfList = function(){
var itemsWidth = 0;
$('.list li').each(function(){
var itemWidth = $(this).outerWidth();
itemsWidth+=itemWidth;
});
return itemsWidth;
};
var widthOfHidden = function(){
return (($('.wrapper').outerWidth())-widthOfList()-getLeftPosi())-
scrollBarWidths;
};
var getLeftPosi = function(){
return $('.list').position().left;
};
var reAdjust = function(){
if (($('.wrapper').outerWidth()) < widthOfList()) {
$('.scroller-right').show();
}
else {
$('.scroller-right').hide();
}
if (getLeftPosi()<0) {
$('.scroller-left').show();
}
else {
$('.item').animate({left:"-="+getLeftPosi()+"px"},'slow');
$('.scroller-left').hide();
}
}
reAdjust();
$(window).on('resize',function(e){
reAdjust();
});
$('.scroller-right').click(function() {
$('.scroller-left').fadeIn('slow');
$('.scroller-right').fadeOut('slow');
$('.list').animate({left:"+="+widthOfHidden()+"px"},'slow',function(){
});
});
$('.scroller-left').click(function() {
$('.scroller-right').fadeIn('slow');
$('.scroller-left').fadeOut('slow');
$('.list').animate({left:"-="+getLeftPosi()+"px"},'slow',function(){
});
});
}
}
and run the method on mount like this:
mounted() {
this.renderStuff();
}
Side note, var is not ideal in this day and age. Recommend converting these to let.

Pug Unbuffered Code Variable Interpolation Not Working but Buffered Code does

I'm trying to create an express app using Pug for templating. I cannot figure out why when I am using an unbuffered variable interpolation, the object is undefined but when I remove the dash it seems to work just fine (minus that it literally displays the object)
//index.pug
extends layout
block campground
- var campgrounds = '#{camps}'
.row
each campground in campgrounds
div.col-md-3.col-sm-6
div
img(src=`${campground.image}` class='img-thumbnail')
a(href=`/campgrounds/${campground._id}`)
h4.caption.text-center #{campground.name}
//app.js
app.get('/campgrounds', async (req, res) => {
try {
const camps = await Camp.find();
res.render('index', { camps: camps });
} catch (ex) {
res.status(500).send('internal error');
}
});
Syntax 1:
- var campgrounds = '#{camps}'
Produces:
Syntax 2:
var campgrounds = '#{camps}'
Produces:
I believe that you can:
Remove the row - var campgrounds = '#{camps}' and replace the row each campground in campgrounds on each campground in camps (see the code snippet below).
Or you also can replace - var campgrounds = '#{camps}' on - var campgrounds = camps (you don't need interpolation in code rows).
$(function() {
// in your code you get `camps` from DB
// const camps = await Camp.find();
const camps = [{name: 'Camp1'}, {name: 'Camp2'}, {name: 'Camp3'}];
var json = {
camps: camps
};
// jade compile
// instead of your function res.render(...);
$("#so").html(jade.compile($("#jadehi").html())(json));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jade/0.27.7/jade.min.js"></script>
<div id="so">SEO(please enable javascript~)</div>
<pre id="jadehi" style="display:none">
.content
.row
each campground in camps
div.col-md-3.col-sm-6
div.
Campground: #{campground.name}
<!-- img(src=`${campground.image}` class='img-thumbnail') -->
<!-- a(href=`/campgrounds/${campground._id}`) -->
<!-- h4.caption.text-center #{campground.name} -->
</pre>

How to Use ParsleyJS with Browserify

I'm trying to browserify a module containing both jquery and parsleyjs. So far I have this:
var $ = require('jquery');
require('parsleyjs');
If I load this alone, the following line in ParsleyJS throws an ReferenceError jQuery is not defined exception:
window.ParsleyConfig.i18n.en = jQuery.extend(window.ParsleyConfig.i18n.en || {}, {
I think I can use browserify-shim to put jQuery and ParsleyConfig in the global scope, but I could use some help with the details. Also I would prefer a solution that avoids polluting the global scope.
TIA,
- Ole
I will explain my own experience with this problem.
This is not the best way to manage this, I will leave here some clues:
Setup
npm init
npm install --save jquery
npm install --save parsleyjs
app.js
var $ = require('jquery');
window.jQuery = $;
require('parsleyjs/src/i18n/es.js')
require('parsleyjs');
window.Parsley.setLocale('es');
var userFormValidator = require('./validators/userFormValidator.js');
var hello = require('./functions/hello.js');
//global.window.hello = hello;
if (typeof global.window.define == 'function' && global.window.define.amd) {
global.window.define('hello', function () { return hello; });
global.window.define('userFormValidator', function () { return userFormValidator; });
} else {
global.window.hello = hello;
global.window.userFormValidator = userFormValidator;
}
functions/hello.js
module.exports = function () {
alert('hola');
}
validators/userFormValidator.js
module.exports = (function ($) {
var _settings = {};
var _rules = {};
var init = function(settings) {
_settings = {
form : $('#usersForm'),
};
_rules = {
fullname : {
minlength : 3,
maxlength : 80,
required : "true",
},
email: {
minlength : 3,
maxlength : 255,
type : "email",
required : "true",
},
};
_setup();
};
var _setup = function () {
_settings.form.parsley();
var validate = require('./validator.js');
validate(_rules);
};
return {
init: init,
};
})(window.jQuery);
validators/validator.js
var $ = require('jquery');
module.exports = function (rules) {
$.each( rules, function( field, constraints) {
$.each( constraints, function( constraint, value) {
$('[name="' + field +'"]').attr('data-parsley-' + constraint, value);
}.bind(field));
})
}.bind($);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="usersForm">
<label for="fullname">Full Name * :</label>
<input type="text" name="fullname" />
<label for="email">Email * :</label>
<input type="text" name="email" />
<input type="submit" />
</form>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript">
userFormValidator.init();
</script>
</body>
</html>
Turn out that the ParsleyJS project has a test browserify.js that shows how to use ParsleyJS with browserify. It does attach all the ParsleyJS objects to the window object, and requires that jQuery do so as well, but at least it works. If anyone has a solution that does this without attaching to the window, please share.
Here are the steps you need to follow to get it working:
mkdir parsleyjs-test
cd parsleyjs-test
npm init (Answer the questions)
npm install --save jquery
npm install --save parsleyjs
npm install --save-dev beefy
touch index.js
CONTENTS OF index.js
window.jQuery = $ = require('jquery');
require('parsleyjs');
TEST WITH BEEFY:
beefy index.js 8080
View results at:
http://localhost:8080
You should see both jQuery and Parsleyjs in the global window namespace. Use ctrl-shift-I to open the web developer tooling in firefox and click on console. Type window in the command line (Bottom of firefox console) and you will see window.jQuery and window.Parsley, etc.
Cheers,
Ole

how to use less mixins file in my code?

here is my code
var parser = window.less.Parser();
try{
parser.parse(aztp_css_editor.getValue(), function(error, result){
if(!error){
alert(result.toCSS());
}else{
alert(error);
}
});
}catch(error){
alert(error);
}
I have a mixins less file here http://lessprefixer.com/ for shorthand css3 prefix, how I setup it into my parse less code?
I think you should better the less.render function, see also: http://lesscss.org/usage/#programmatic-usage.
But indeed you can use the #import directive as already made clear by #seven-phases-max.
Example:
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.1.0/less.min.js"></script>
<script>
less.render('#import "test.less"; p {color: #red; }', {'include-path': 'test/'})
.then(function(output) {
// output.css = string of css
// output.map = string of sourcemap
// output.imports = array of string filenames of the imports referenced
console.log(output.css);
},
function(error) {
});
</script>
The above compiles well (results in output.css) when test.less is available in the same path as the html which contains the code. You can also use a path in your import, '#import "path/test.less"; I did not found that setting include-path has any effect.

Unable to print output to the console in dojo

I'm a beginner in dojo, and I'm trying to print the output to console using dojo code. But I don't what's the problem in the following code, and how can I print the output to the console?
<html>
<head>
<script type = "text/javascript" src = "dojo/dojo.js" data-dojo-config = "async: true, isDebug : true" >
</script>
</head>
<body>
<h1 id = "greeting">Hello</h1>
<script>
define(["dojo/dom"],function(dom) {
var Twitter = declare(null, {username:"defaultusername",
say :function(msg)
{
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});
</script>
</body>
</html>
Use require instead of define:
<script>
require(["dojo/dom", "dojo/_base/declare"], function(dom, declare) {
var Twitter = declare(null, {
username: "defaultusername",
say :function(msg) {
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});
</script>
Console works, but your code inside callback function in declare is not being executed until you require it.
You cannot define in inline script code, that is meant to be a class define, put in the topmost line of a class-file, meaning define maps the filename to the returned value of its function.
This means, if you have
dojo_toolkit /
dojo/
dijit/
dojox/
libs/
myWidgets/
foo.js
And foo.js reads
define(["dijit._Widget"], function(adijit) {
return declare("libs.myWidgets.foo", [adijit], function() {
say: function(msg) { console.log(msg); }
});
});
Then a new module is registered, called libs / myWidgets / foo. You should make sure that the returned declare's declaredClass inside each define matches the file hierachy.
That being said, reason why define does not work for you is the explaination above. It is inline and has no src to guess the declaredClass name from. Rewrite your code to define("aTwitterLogger", [":
define("aTwitterLogger", ["dojo/_base/declare", "dojo/dom"],function(declare, dom) {
var Twitter = declare(null, {
username:"defaultusername",
say :function(msg)
{
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});