When I open console of Chrome 14 and type...
require (or require(), if that matters)
I get: ReferenceError.
This means that JavaScript doesn't have that function by default, right? At least on web browsers.
Why I'm talking about that?
I needed Markdown parser for JavaScript.
What to do?
I, as usually, opened GitHub and searched for it. The first results that matched my needs was this and this.
Usually (I'm not that good with JavaScript) I include script I want to use before my code using <script /> tag and then... well - use it. But this time I don't get what's happening... :(
Usage for #1 script:
var input = "# Heading\n\nParagraph";
var output = require( "markdown" ).toHTML( input );
print( output );
Usage for #2 script:
var marked = require('marked');
console.log(marked('i am using __markdown__.'));
Where does that require() came from? Thanks in an advice! :)
It's a way to include node.js packages. Luckily, the first package you linked to, markdown-js, is very smart. It checks whether it is included as a node package, and if not, will set the markdown object to window.markdown. So all you have to do is include this file in a <script> tag and you should be able to use the markdown object from the global scope.
From the page you link to:
The simple way to use it with CommonJS is:
Looks like require comes from CommonJS
Related
I'm trying to move my workspace to c9 because the Ace editor's autocompletion really pleased me when I worked on NodeJS projects.
But now I would like to work on JS files client-sided. It is from this point autocompletion going wrong. Indeed, there is nothing such as "require" command in client-side JS inside of the JS files themselves (except using some plugins) to inform of the other source files used in.
So when I use, in one of my JS files, a function that is defined in an other file (even libraries, frameworks : jquery, etc), Ace notifies me that the function is not defined (cause it has no way to know that the function is defined in another file, I guess).
Here we go : is there some comment line I could put in my code, or some configuration of c9 I could set, to correct that behavior ?
To remove the errors and warning, you can just add the following line near the top of your javascript file:
/* globals jquery lodash someOtherLibrary */
However, Cloud9 doesn't do autocomplete for client side libraries yet.
Abuse C9's require support
When you use var yourLibrary = require("./somefile.js");, auto-completion works perfectly.
But, as you stated, require() doesn't exist, nor do you want to have yourLibrary set to undefined. (Or to just throw an error)
As it turns out, C9 isn't that smart:
//Your library was defined in some other file
var yourLibrary; //"This does nothing other than making C9 happy
function require() {return 1;} //Define the require function
if(false) {
yourLibrary = require("yourLibraryFile.js");
}
Now, you can use autocomplete (it even shows the documentation comments)!
Note: It doesn't always work.
I tried something like:
var path = '../right/here';
var module = require(path);
but it can't find the module anymore this way, while:
var module = require('../right/here');
works like a charm. Would like to load modules with a generated list of strings, but I can't wrap my head around this problem atm. Any ideas?
you can use template to get file dynamically.
var myModule = 'Module1';
var Modules = require(`../path/${myModule}`)
This is due to how Browserify does its bundling, it can only do static string analysis for requirement rebinding. So, if you want to do browserify bundling, you'll need to hardcode your requirements.
For code that has to go into production deployment (as opposed to quick prototypes, which you rarely ever bother to add bundling for) it's always advisable to stick with static requirements, in part because of the bundling but also because using dynamic strings to give you your requirements means you're writing code that isn't predictable, and can thus potentially be full of bugs you rarely run into and are extremely hard to debug.
If you need different requirements based on different runs (say, dev vs. stage testing vs. production) then it's usually a good idea to use process.env or a config object so that when it comes time to decide which library to require for a specific purposes, you can use something like
var knox = config.offline ? require("./util/mocks3") : require("knox");
That way your code also stays immediately traversable for others who need to track down where something's going wrong, in case a bug does get found.
require('#/path/'.concat(fileName))
You can use .require() to add the files that you want to access calculating its path instead of being static at build time, this way this modules will be included and when calling require() later they will be found.
Is there any way I can include an external JS library in my pebble code?
Conventionally on a webpage I would do this in my head tags:
<script type='text/javascript' src='https://cdn.firebase.com/js/client/1.0.11/firebase.js'></script>
But in pebble, I am unable to do that since I am only using JS. So how can I include an external library for a JavaScript file.
At present, you cannot include external JS files.
If you're using CloudPebble, then the only way to do this is to copy and paste the content of the JS library files into your JS file.
If you're doing native development, you can modify the wscript file to combine multiple JS files into one at build time.
I think there's some confusion over Pebble.js vs PebbleKit JS (v3.8.1). Pebble.js is a fledgling SDK where eventually the programmer will be able to write pure JavaScript. It's still cooking so there's some functionality missing like the ability to draw a line or obtain the screen dimensions. The repo is a mix of C and JS sources where you can add C code to augment missing functionality but otherwise all your code lives in src/js/app.js or src/js/app/. Anyway, Pebble.js does support require.
I don't use CloudPebble but I got the impression that it either supports Pebble.js (and hence require) or is planning to. I think all this SDK boilerplate code would be hidden.
PebbleKit JS does not support require out of the box AFAIK. I've made a demo that ports require support from Pebble.js to PKJS. The summary of changes is:
Move your project's src/js/pebble-js-app.js to src/js/app/index.js.
Remove any ready event listener from src/js/app/index.js. index.js will
be loaded when the ready event is emitted.
Add src/js/loader.js from Pebble.js.
Add a src/js/main.js that calls require('src/js/app') on the ready event.
Update your wscript with the following
deltas.
When adding new modules, place them under src/js/app/ and require('./name') will work.
I've tried to cover this all in the demo's readme.
BTW, here's the official breakdown of all the different SDKs but it's a little confusing.
I am not sure if there have been changes since the above answer, but it looks like there is in fact a way to include additional resources while keeping things tidy. On the pebbleJS page, there is the following section with an some information on the subject.
GLOBAL NAMESPACE - require(path)
Loads another JavaScript file allowing you to write a multi-file project. Package loading loosely follows the CommonJS format. path is the path to the dependency.
You can then use the following code to "require" a JS library in your pebble project. This should be usable on both Cloud Pebble as well as native development.
// src/js/dependency.js
var dep = require('dependency');
You can then use this as shown below:
dep.myFunction(); // run a function from the dependency
dep.myVar = 2; // access or change variables
Update:
After some digging into this for my own, I have successfully gotten CloudPebble to work with this functionality. It is a bit convoluted, but follows the ECMAScript 6 standards. Below I am posting a simple example of getting things set up. Additionally, I would suggest looking at this code from PebbleJS for a better reference of a complex setup.
myApp.js
var resource = require('myExtraFile'); // require additional library
console.log(resource.value); // logs 42
resource.functionA(); // logs "This is working now"
myExtraFile.js
var myExtraFile = { // create a JSON object to export
"value" : 42, // variable
functionA : function() { // function
console.log("This is working now!");
}
};
this.exports = myExtraFile; // export this function for
// later use
I'm trying to find a way to programatically get the last value returned by the Javascript interpreter. Ruby's interpreter, to name an example, has the "_":
1 + 2 #=> 3
_ #=> 3
I would like to know if the same thing exists in Javascript.
EDIT:
Another way to maybe achieve this. Is there any syntax that supports the continuation of an expression in a newline? Something like this:
var a = \&
1 + 2;
a #=> 3
Some sort of combination of characters that tell the interpreter the expression continues in a newline (like the + for string concatenation).
PURPOSE:
Purpose of this research is to find if I can load a JSON data structure using a script tag and successfully assign it from outside of its scope, something like this:
<script> var json_struct = </script>
<script src="http://domain.com/myjsonfile.json" type='application/json' ></script>
which, by the way, doesn't work. Surprisingly :)
PURPOSE:
Purpose of this research is to find if I can load a JSON data structure
using a script tag and successfully assign it from outside of its scope
There is no construct in browser based javascript that can do this.
The reason is that browsers, since the earliest Netscape days, have always initiated the script compiler upon the closing of the script tag. Regardless if it's javascript, VBscript (IE only) or Tcl (with the appropriate plugin).
Which means that any statement that is incomplete will simply be treated as a syntax error. Each <script> tag is basically treated as a single file.
What you're trying to do is similar to this in Ruby:
a = require 'one_plus_two.rb'
which I don't think works in Ruby.
However, in non-browser environments that support modules like Node.js, the method that imports module does in fact return a value (usually an object). So you can do something like this in node.js:
var a = require('my_data_file.js');
Unfortunately, the require function only works on local files. But Node.js is open source so you can always fork it and modify require to be able to source from http:// like PHP.
Alas, if what you're trying to do is browser scripting then the above point is moot.
I am scripting java using rhino. I have few classes written in java that I am importing in javascript.
But, when I am validating javascript against JSLint, it invalidates javascript saying:
Problem at line 9 character 1: 'importPackage' was used before it was defined.
Here is the sample from my script:
importPackage(Packages.org.raj.test);
var test = "123";
I have selected the option: "Assume Rhino" as well but still, it shows up same error.
How should I deal with this problem?
Note that the ECMA standard doesn't cover communication with Java (or with any external object system for that matter).
I have explicitly added following line on top of my script
/*global importPackage: true */
and it works!
It looks like the "Assume Rhino" flag (aka rhino: true in the options directive) only predefines a few global variables for you, and importPackage isn't one of them. You can see the complete list in the code.
Paul's answer is basically the correct workaround – you just manually declare each extra global you use. This code passes JSLint cleanly:
/*global importPackage, Packages */
importPackage(Packages.org.raj.test);
var test = "123";