I'm creating a node application using CoffeeScript and have run into a syntactic question. Basically, I have a simple file (foo.js) with an export that looks like this.
foo = {}
exports.foo = foo
Now, in a separate file, I want to create the equivalent syntax to this, but in CoffeeScript.
var bar = require('./foo').foo;
So that bar is automatically assigned to the variable foo in foo.js. However, I'm not sure what the proper CoffeeScript to do this is. I've tried doing something like.
bar = require './foo'.foo
But node yells at me, saying that it can't find the proper module. Given that, is there any way for me to achieve my desired result just using pure CoffeeScript.
Sometimes you just need to use parens. The code you gave:
bar = require './foo'.foo
compiles to something that is clearly not what you want:
var bar;
bar = require('./foo'.foo);
You'll need to do something like
bar = require('./foo').foo
In the future, I would suggest using the in-browser CoffeeScript compiler at http://jashkenas.github.com/coffee-script/ to check that code is compiling as you expect.
Related
I'm kind of going nuts here.
I need to start writing a stand alone non web application in JavaScript.
My problem is that I can run (using nodejs) the script just fine, but I can't split the code that I need to write among multiple files because then I don't know how to include them.
Rigth now all I want is the simplest working example of including a JS file inside another so I can use the functions defined there (or class if I so choose).
My test.js looks like this.
const { outputText } = require("./text_module.node.js");
outputText();
While my text_module.node.js looks like this:
function outputText(){
console.log("hello world");
}
My package.json looks like this:
{
"type": "text_module.node.js"
}
I have tried
Adding export before the function. It tells me export is unexpected
Using this notation: import { something } from "a_path". Anything that uses this notation will get me an "Unexpected token {" error.
The current configuration simply tells me that outputText() is not a function. So I'm out of ideas.
I don't know how else to search. I've been searching for hours on this topic and it seem that no matter where I look there is some HTML code that is needed to tie everything togeter or using another third party tool. Using jQuery loads stuff "asynchronically" which is not what I need. I want it to sequential.
Is JS just NOT suppossed to be used like other scripting languages? Otherwise I can't figure out why this is so complicated. I feel like I'm missing something big here.
If you want to use const { outputText } = require("./text_module.node.js");,
export it as module.exports = { outputText: outputText }.
In your question,
Adding export before the function. It tells me export is unexpected
Because it's an es6 thing and nodejs doesn't support all es6 features. You can refer to this answer for more details on that.
I have a pretty big javascript legacy code base of a WebApplication, which includes the presentation/data model/controller/connectivity. I'm trying to replace the presentation layer technology with ReactNative, while keep the existing data model/controller/connectivity parts. So the first question is, after I built the ReactNativeComponent where we have the UI layout defined, binding established, styles created... but I need to call some js functions from the legacy code.
How can I require/import an existing js file (not a ReactNativeComponent) to one ReactNativeComponent and use it?
I've had this problem before too. Something I did, unable to find more elegant solutions, was to wrap my legacy code in a module.
Let's say this is foo.js
var Foo = (function() {
var mod = {
init: function() {
// legacy code here...
}
}
return mod;
})()
module.exports = Foo;
then in calling file:
import foo from './somewhere/foo';
foo.init();
I didn't love this approach, but it worked. Hopefully it can somewhat help.
If they're purely js then you can import them normally. If they have anything to do with html/css/dom it will throw an error.
So I'm working with an enterprise tool where we have javascript scripts embedded throughout. These scripts have access to certain built-in objects.
Unfortunately, the tool doesn't give any good way to unit test these scripts. So my thinking was to maintain the scripts in a repo, mock the built-in objects, and then set up unit tests that run on my system.
I'm pretty ignorant to how JavaScript works in terms of building, class loading, etc. but I've been just trying things and seeing what works. I started by trying out Mocha by making it a node project (even though it's just a directory full of scripts, not a real node project). The default test works, but when I try and test functions from my code, I get compiler errors.
Here's what a sample script from my project looks like. I'm hoping to test the functions, not the entire script:
var thing = builtInObject.foo();
doStuff(thing);
doMoreStuff(thing);
function doStuff(thing) {
// Code
}
function doMoreStuff(thing) {
// More Code
}
Here's what a test file looks like:
var assert = require('assert');
var sampleScript = require('../scripts/sampleScript.js');
describe('SampleScript', function() {
describe('#doStuff()', function() {
it('should do stuff', function() {
assert.equal(-1, sampleScript.doStuff("input"));
});
});
});
Problem happens when I import ("require") the script. I get compilation errors, because it doesn't builtInObject. Is there any way I can "inject" those built in objects with mocks? So I define variables and functions that those objects contain, and the compiler knows what they are?
I'm open to alternative frameworks or ideas. Sorry for my ignorance, I'm not really a javascript guy. And I know this is a bit hacky, but it seems like the best option since I'm not getting out of the enterprise tool.
So if I get it right you want to do the unit tests for the frontened file in the Node.js environment.
There are some complications.
First, in terms of Node.js each file has it's own scope so the variables defined inside of the file won't be accessible even if you required the file. So you need to export the vars to use them.
module.exports.doStuff = doStuff; //in the end of sample script
Second, you you start using things like require/module.exports on the frontend they'll be undefined so you'll get an error.
The easiest way to run your code would be. Inside the sample script:
var isNode = typeof module !== 'undefined' && module.exports;
if (isNode) {
//So we are exporting only when we are running in Node env.
//After this doStuff and doMoreStuff will be avail. in the test
module.exports.doStuff = doStuff;
module.exports.doMoreStuff = doMoreStuff;
}
What for the builtInObject. The easies way to mock it would be inside the test before the require do the following:
global.builtInObject = {
foo: function () { return 'thing'; }
};
The test just passed for me. See the sources.
Global variables are not good anyway. But in this case seems you cannot avoid using them.
Or you can avoid using Node.js by configuring something like Karma. It physically launches browser and runs the tests in it. :)
I'm trying to get intellisense in visual studio code. The following code works fine:
var Bar = function(){
}
Bar.prototype.logMsg = function(msg){
console.log(msg);
}
Intellisense working
But I don't recive any intellisense when writing:
var FOO = {};
FOO.Bar = function(){
}
FOO.Bar.prototype.logMsg = function(msg){
console.log(msg);
}
Not working
This might be due to restrictions I'm not aware of, but I can't find any documentation/posts mentioning this. Is there a way to get it working without rewriting big parts?
I work on TypeScript and JavaScript support in VSCode. As of VSCode 1.8.1, this type of dynamic property assignment is not something that our IntelliSense recognizes.
We use TypeScript to power both our TypeScript and JavaScript IntelliSense, and while TypeScript is able to recognize the common prototype pattern shown in your first example, it does not recognize properties added to an object, as in your second example. This means that FOO.Bar will always have an any type.
We're tracking support for this type of IntelliSense in the TypeScript project: https://github.com/Microsoft/TypeScript/issues/13271
In my Meteor projects I have several helper functions of the sort
helpers.js
var tagStr = function () { return this.tags.join(', '); };
articles.js
Template.articles.tags = tagStr;
listing.js
Template.listing.tags = tagStr;
Now, I can define the function in either articles.js or listing.js, and it won't work in the other one. Or i can define it in helpers.js and it will work in neither..
So, how would I go about loading my helper functions before the rest of the scripts? Preferably in "the right way".
Thanks!
i think what you are looking for is a globally available handlebars helper - i keep mine in client/lib/handlebars.js - the contents of the 'lib' folder will get loaded first
define each helper like so:
Handlebars.registerHelper("joinArray", function(array) {
if(array)
return array.join(', ');
});
you would then use this in any template html file like so:
{{joinArray tags}}
you can read more about handlebars helpers here handlebarsjs.com/block_helpers.html
this is the 'right' way IMO, but if you want to use normal javascript functions and not handlebars helpers, that works also
you'll need to place the commonly used javascript function in a file like client/lib/helpers.js and do NOT use the 'var' declaration prefix
like so:
thisIsAGloballyAvailableFunction = function(){...};
not like:
var thisFunctionIsOnlyAvailableInThisFile = function(){...};
meteor does a slightly strange thing to control scoping. anything with 'var' is local to the scope of the file it occurs in, anything declared without 'var' is globally available across the app
The answer by nate-strauser was correct and helped me find the right solution but now (Meteor 1.0) Handlebars.registerhelper() is deprecated.
Now it works this way (if anyone is still interested):
Template.registerHelper()
The rest as explained by nate-strauser.