Jade: ReferenceError: TokContext is not defined - javascript

I make my app.js simplest node server. To do that I installed next libs:
npm install node-jsx react express jade.
Now when I start it with node app.js it gets the next error:
c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:2275
_classCallCheck(this, TokContext);
^
ReferenceError: TokContext is not defined
at new TokContext (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:2275:25)
at Object../state (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:2285:11)
at s (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:1:681)
at c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:1:732
at Object../expression (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:907:21)
at s (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:1:681)
at e (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:1:852)
at c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:1:870
at a (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:1:150)
at Object.<anonymous> (c:\Programming\React_Examples\server rendering\node_modules\jade\node_modules\constantinople\node_modules\acorn\dist\acorn.js:1:383)

The issue is a conflict between the node-jsx and acorn modules (the latter used by Jade).
If you can save all your JSX in files whose extension is something other than .js, say .jsx, you could replace your
require('node-jsx').install();
call with:
require('node-jsx').install({extension: '.jsx'});
Another alternative might be a different templating engine from Jade.
Or limiting your JSX includes to modules outside of your main one (not sure about this one, but worth trying if necessary).
See https://github.com/pugjs/jade/issues/1925

Related

How to get Jest to see the functions I am writing for MongoDB Stitch?

I am trying out Stitch, a serverless/hosted JavaScript environment from MongoDB. My main purpose is to help me learn modern JavaScript, but I am trying to write a useful app as well.
I have written the following function, and saved it in my Stitch app. I believe this follows the documented way to write functions in Stitch, and I have tested it from the Stitch administration console:
exports = function(query){
const http = context.services.get("HTTP");
const urlBase = context.values.get("stackOverflowApiUrl");
const options = [
'order=desc',
'sort=activity',
'site=stackoverflow',
'q=' + encodeURIComponent(query),
'user=472495',
'filter=!--uPQ.wqQ0zW'
];
return http
.get({ url: urlBase + '?' + options.join('&') })
.then(response => {
// The response body is encoded as raw BSON.Binary. Parse it to JSON.
const ejson_body = EJSON.parse(response.body.text());
return ejson_body.total;
});
};
This code is pretty simple - it obtains an http object for making external API fetches, and obtains a configuration value for a URL urlBase to contact (resolving to https://api.stackexchange.com/2.2/search/excerpts) and then makes a call to the Stack Overflow Data API. This runs a search query against my user and returns the number of results.
So far so good. Now, I want to call this function locally, in Jest. To do this, I have installed Node and Jest in a local Docker container, and have written the following test function:
const callApi = require('./source');
test('Simple fetch with no user', () => {
expect(callApi('hello')).toBe(123);
});
This fails, with the following error:
~ # jest
FAIL functions/callApi/source.test.js
✕ Simple fetch with no user (3ms)
● Simple fetch with no user
TypeError: callApi is not a function
2 |
3 | test('Simple fetch with no user', () => {
> 4 | expect(callApi('hello')).toBe(123);
| ^
5 | });
6 |
at Object.<anonymous>.test (functions/callApi/source.test.js:4:12)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.418s
Ran all test suites.
(In fact I was expecting it to fail, since it contains a global object context that Jest does not have access to. I will work out how to mock that later, but for now Jest cannot even see the function at all).
I suspect I can see the reason - in the Jest introduction docs, one has to do this for the SUT:
module.exports = function() { ... }
However the Stitch docs seem to require functions to be defined as:
exports = function() { ... }
I do not have a background in JavaScript to understand the difference. I could try module.exports in Stitch, but I would rather not, since this would either not work now, or cause a breakage in the future. Can Jest be instructed to "see" bare exports without the module prefix?
Incidentally, I have picked Jest because it is popular, and because some of my JavaScript colleagues vouch for it. However, I am not wedded to it, and would be happy to use something else if it is known to be better for Stitch development.
Update
Following the useful answer from jperl below, I find that the following construction is not possible in Stitch:
module.exports = exports = function() {}
I also cannot do this:
exports = function() {}
module.exports = exports
If I try either, I get the following error:
runtime error during function validation
So it looks like I have to get Jest to work without module.exports, or create a glue file that imports the exports version into module.exports, with the main file being used by Stitch, and the glue importer being used by Jest.
I suggest you to read this thread. And you're right in thinking it has to do with modules.exports vs exports. The thing is that module.exports and exports first point to the same thing. So something like this works:
//modify the same object that modules.exports is pointing to
exports.a = {}
exports.b = {}
but this won't:
exports = {}
Why? Because now exports points to something else than module.exports so what you're doing has no effect at all.
Update
Following some updates in the comments, we came to the view that Stitch does not seem to support the export format that Jest requires.
This is an addendum to jperl's answer, to show how I got Jest working while respecting Stitch's limitations.
Firstly, it is worth noting how a Stitch application is laid out. This is determined by the import/export format.
auth_providers/
functions/
function_name_1/
config.json
source.js
function_name_2/
config.json
source.js
...
services/
values/
The config.json file is created by Stitch remotely, and is obtained through a export. This contains ID information to uniquely identify the function in the same folder.
I believe it is common JavaScript practice to mix tests with source code, so I am following that style (I am new to modern JS, and I confess I find this style untidy, but I am running with it nevertheless). Thus I add a source.test.js file in each function folder.
Finally, since there is a discrepancy between what Stitch requires and what Jest requires, I have written a script to create a source code file under _source.js in each function folder.
So, each folder will contain these files (the underscore files will probably be ignored by Git, as they will always be generated):
_source.js
config.json
source.js
source.test.js
In order to create the underscored copies, I am using this shell script:
#!/bin/bash
# Copy all source.js files as _source.js
for f in $(find functions/ -name source.js); do cp -- "$f" "$(dirname $f)/_$(basename $f)"; done
# Search and replace in all _source.js files
for f in $(find functions/ -name _source.js); do sed -i -e 's/exports =/module.exports =/g' $f; done
A bit hacky perhaps, but it works!

Integrating React components with Pux - where does require() come from?

The Pux documentation tells me to use require() in the browser. Where does that function come from and how do I use it?
Background:
I'm trying to integrate the Quill editor with my web application that uses purescript-pux.
Following the Pux documentation I created a file MyEditor.js like this:
// module MyEditor
var React = require("react");
var Pux = require("purescript-pux");
var MyEditor = React.createClass({
displayName: "MyEditor",
onTextChange: function onTextChange(value) {
this.setState({ text: value });
},
render: function render() {
return React.createElement(ReactQuill, { value: this.state.text,
onChange: this.onTextChange });
}
});
exports.fromReact = Pux.fromReact(MyEditor);
and a file MyEditor.purs as follows:
module MyEditor where
import Pux.Html (Html, Attribute)
foreign import fromReact :: forall a. Array (Attribute a) -> Array (Html a) -> Html a
I then use MyEditor.fromReact [value p.description] in my Html Action and the code compiles, but the browser complains about ReferenceError: require is not defined.
I'm not very familiar with the javascript ecosystem. I'm aware that several libraries providing a require() function exist, but which one do I use with Pux and how?
require is the NodeJS way of importing modules, it's not supported in the browser so you'll need to run your project through a bundler like browserify or webpack to produce a bundle that the browser can understand.
If you are using the pulp build tool it's as simple as running
pulp browserify --to app.js
and then loading app.js in your html through a script tag.
pulp browserify documentation: https://github.com/bodil/pulp#commonjs-aware-builds
In addition to Christophs answer (but can't comment since comments don't allow code blocks):
Using Thermite 4.1.1 this worked for me:
add a package.json file with:
{
"dependencies": {
"react": "^0.14",
"react-dom": "^0.14"
}
}
run npm install
from then on pulp browserify --optimise gets the whole shebang packaged.
This is really badly documented and I opened an issue about that on purescript-react.

NodeJs : TypeError: require(...) is not a function

I am trying to require a file and afterwards pass it to a var. I am following this tutorial to create an authentication system. After writing the server.js file and trying to compile I got a BSON error therefore I changed the line that required the release version of it in mongoose.
Here are my code and error:
server.js
require('./app/routes')(app, passport);
Error
require('./app/routes')(app, passport);
^
TypeError: require(...) is not a function
at Object.<anonymous> (d:\Node JS learning\WorkWarV2\server.js:38:24)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
Process finished with exit code 1
I have read that this usually means that requireJS is not getting loaded properly yet I am not aware why or how to fix it.
Edit due to comment:
As asked, here is the result of console.log(require);
For me, when I do Immediately invoked function, I need to put ; at the end of require().
Error:
const fs = require('fs')
(() => {
console.log('wow')
})()
Good:
const fs = require('fs');
(() => {
console.log('wow')
})()
I think this means that module.exports in your ./app/routes module is not assigned to be a function so therefore require('./app/routes') does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport).
Show us ./app/routes if you want us to comment further on that.
It should look something like this;
module.exports = function(app, passport) {
// code here
}
You are exporting a function that can then be called like require('./app/routes')(app, passport).
One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B) and module B is trying to require(A). When this happens, it will be detected by the require() sub-system and one of them will come back as null and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.
For me, this was an issue with cyclic dependencies.
IOW, module A required module B, and module B required module A.
So in module B, require('./A') is an empty object rather than a function.
How to deal with cyclic dependencies in Node.js
Remember to export your routes.js.
In routes.js, write your routes and all your code in this function module:
exports = function(app, passport) {
/* write here your code */
}
For me, I got similar error when switched between branches - one used newer ("typescriptish") version of #google-cloud/datastore packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports value. I got the error because node_modules still had newer modules used by branch I switched from.
I've faced to something like this too.
in your routes file , export the function as an object like this :
module.exports = {
hbd: handlebar
}
and in your app file , you can have access to the function by .hbd
and there is no ptoblem ....!
I don't know how but in may case it got fixed when I changed
require('./routes')(app)
to
require('./routes')
In my case i fix when i put the S in the module.exportS,
BEFORE:
module.export = () => {}
AFTER:
module.exports = () => {}

Meteor: TypeError: Object #<Object> has no method 'require'

I had problems previously trying to get the Meteor.require method to work and I thought it was fixed but apparently not. Although I have since upgraded to Meteor 0.9.0.
Anyone have any idea how I can get the Meteor.require method to work?
Here's what I get on the terminal when passing params back to the server
=> App running at: http://localhost:3000/
I20140827-11:08:21.949(-7)? createImage
I20140827-11:08:21.953(-7)? 24890
I20140827-11:08:22.030(-7)? Exception while invoking method 'createImage' TypeError: Object #<Object> has no method 'require'
I20140827-11:08:22.032(-7)? at Meteor.methods.createImage (app/server/server.js:7:21)
I20140827-11:08:22.033(-7)? at maybeAuditArgumentChecks (packages/livedata/livedata_server.js:1492)
I20140827-11:08:22.034(-7)? at packages/livedata/livedata_server.js:643
I20140827-11:08:22.034(-7)? at _.extend.withValue (packages/meteor/dynamics_nodejs.js:56)
I20140827-11:08:22.034(-7)? at packages/livedata/livedata_server.js:642
I20140827-11:08:22.034(-7)? at _.extend.withValue (packages/meteor/dynamics_nodejs.js:56)
I20140827-11:08:22.034(-7)? at _.extend.protocol_handlers.method (packages/livedata/livedata_server.js:641)
I20140827-11:08:22.035(-7)? at packages/livedata/livedata_server.js:541
This is my Meteor.method:
createImage: function(coords) {
console.log('createImage')
console.log(coords.area);
var gd = Meteor.require('node-gd');
},
my packages.json file:
{
"node-gd":"0.2.3"
}
node-gd is definitely there too:
me#ubuntu:~/leaderboard/packages/npm/npm/node_modules/node-gd$ ls
binding.gyp build coffee cpp js package.json README.md
Meteorhacks just released (I'm talking about 4 hours ago) the updated npm package for Meteor 0.9, it's called meteorhacks:npm https://github.com/meteorhacks/npm
You should remove the previous package which I suppose is broken (something like arunoda:npm I guess) and give the new one a try.
Be aware that Meteor.require has been replaced by Meteor.npmRequire !

Using NPM package on Meteor's Template

I've added the moment package using mrt add moment to format dates/times on the clientside within Meteor's templates. However I seem to be able to use it on the serverside but not within the template helpers.
How can I use momentjs within the template helpers?
server/main.js (Works!)
var moment = Meteor.require('moment');
var t = moment( '2013-11-24 16:18:06' ).format('HH:mm:ss');
console.log(t);
client/main.js (Does not work)
Template.fruits.myTime = function() {
var moment = Meteor.require('moment');
var t = moment( '2013-11-24 16:18:06' ).format('HH:mm:ss');
return t;
}
Error:
Uncaught ReferenceError: require is not defined
I tried using Npm.require('moment') which gave an error: Uncaught ReferenceError: Npm is not defined
and Meteor.require('momemt') which gave an error: Uncaught TypeError: Object #<Object> has no method 'require'
If you add moment using
mrt add moment
then it is available directly as function:
moment()
You can always find out how to use particular package by looking at its package.js file. Take a look at package.js in moment package:
...
if(api.export) {
api.export('moment');
}
...
I noticed that it is very convenient to use moment by registering global handlebars helper:
Handlebars.registerHelper('nice-date', function(date){
return moment(date).fromNow();
});
and using it directly in template:
<template name="test">
{{nice-date createdAt}} // 5 seconds ago
</template>
If you add a Meteor package, you should never need to use require(). How did you add Moment? Via the package on Atmosphere (https://atmosphere.meteor.com/package/moment) using the command mrt add moment?
Per that page, once the package is added you should see a moment global variable that you can simply call:
var oneMonentPlease = moment();
You don't need to put any require statements anywhere. The above line should just work.
Since Moment is a client-side library, you don't necessarily need to add it as a Meteor package or Npm module. You could just download http://momentjs.com/downloads/moment.min.js and save it in your /lib folder. Do that and it will automatically be available to both client and server, and the above line of code will work.

Categories

Resources