How do I use Node.JS modules on my site? - node.js

Okay, let me preface this by saying I am a complete noob when it comes to Node.
I have a Node module, Typed.js, that I want to use on my site, but I'm not sure how. I don't think it'll work out the box since Node is a server-side tool, and you import stuff from the Typed.js package.

You need to wrapper your code up like this
(function(exports){
// your code goes here
})(typeof exports === 'undefined'? this['typed']={}: exports);
Then in your client side
<script src="typed.js"></script>
<script>
console.log(typed.your-function());
</script>

Related

Creating a custom Stripe form with React

What i am trying to do is create a custom stripe form in ReactJS ,i don't want to use react-stripe-elements , i have already built a custom form and after some digging i found a solution that fits my needs but the solution was in vanilla Javascript, so what it does is that it appends a script to the body and creates a global Stripe variable that can you can use to access the Stripe API
import React from "react";
const loadStripe = () => {
if (!window.document.getElementById("stripe-script")) {
var s = window.document.createElement("script");
s.id = "stripe-script";
s.type = "text/javascript";
s.src = "https://js.stripe.com/v2/";
s.onload = () => {
window["Stripe"].setPublishableKey(
"PUBLIC_KEY_HERE"
);
};
window.document.body.appendChild(s);
}
return window.Stripe;
};
export default loadStripe;
and then i use it as
let Stripe = loadStripe();
const onSubmit = (cardNumber,exp_month,exp_year,CVC) =>{
Stripe.card.createToken(
{
number: cardNumber,
exp_month: exp_month,
exp_year: exp_year,
cvc: CVC,
},
(status, response) => {
console.log(status);
console.log(response);}
}
}
the above solution obviously does work but I was hoping that someone could point me in the right direction so that i could get rid of the loadStripe Component and use Something like a npm package or a React Specific solution (because as far as i know i shouldn't be creating and appending scripts in the body using JS)
Any Help would be much appreciated :)
I was hoping that someone could point me in the right direction so that i could get rid of the loadStripe Component and use Something like a npm package or a React Specific solution
If you're looking for an npm package, Stripe recently released their own official library to load Stripe.js which you can find here:
https://www.npmjs.com/package/#stripe/stripe-js
In fact, #stripe/stripe-js works much in the same way as the custom loadStripe function you have now as you can see here:
https://github.com/stripe/stripe-js/blob/master/src/shared.ts#L7-L24
I should note that it's perfectly okay to append scripts in the body using JavaScript as long as you have a good handle on how the script loads (i.e., through async Promises).
That being said, using your loadStripe function or Stripe's official one (#stripe/stripe-js) isn't a requirement. Controlling how and when to inject Stripe.js in the DOM is very helpful when doing server-side rendering (0). But, if that isn't something you're doing, you can just include Stripe.js manually (1) in the <head> of your html like this:
<html>
<head>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
What i am trying to do is create a custom stripe form in ReactJS ,i don't want to use react-stripe-elements
If you are using React v16.8 or greater, the official recommendation would be to use our new React library which you can find here:
https://www.npmjs.com/package/#stripe/react-stripe-js
But if your heart's set on not using either #stripe/react-stripe-js or the older react-stripe-elements library, it is definitely possible to roll your own custom integration. Here's a very bare-bones example of how you could do that:
https://codesandbox.io/s/eager-cdn-krumt
I'm including Stripe.js here: https://codesandbox.io/s/eager-cdn-krumt?file=/public/index.html:1062-1116
And integrating it into a component here: https://codesandbox.io/s/eager-cdn-krumt?file=/src/Checkout.js
Be sure to replace pk_test_xyz with your own publishable key before testing it out.
Hope this helps!
[ 0 ] https://alligator.io/react/server-side-rendering/
[ 1 ] https://stripe.com/docs/js/including

Uncaught SyntaxError: Unexpected token { in import statement

I'm attempting to put my first full-stack application together and am getting an unexpected syntax error:
"Uncaught SyntaxError: Unexpected token {"
The error is coming from this line of code in my map.js file:
import {userInput} from './algorithm/searchingAlgorithm.js';
ejs file:
<head>
<script type="text/javascript" src="../javascripts/map.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCx0LvEwPUgGhpLjCErr24dOnk-VWjo83g&callback=initMap">
</script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
from './algorithm/searchingAlgorithm.js':
export default async function userInput(origin, destination){
I've done a lot of searching and have yet to come up with an answer. I'm using node.js/express and express generator, javascript. I'm also utilizing the google maps api.
The import and export statements are used frequently in web development, but they do not currently work automatically in a browser because they are newer features in the JavaScript language. You need to "build" the code into a format that the browser can execute. Example code on the web tends to assume that you are already doing this.
There are different tools that allow you to do this, such as Rollup or Webpack.
Heads up for anyone running into this issue like I was.
TLDR; make sure to run the import statement from GLOBAL SCOPE.
I ended up trying to insert my first import {test_exported_function} from "./test.js";
from inside of my main function which waits for the DOM content to load before running all of my scripts.
Didn't realize that I needed to execute that line from global scope of the script.
Once I realized that, it suddenly hit me how dumb I was for trying to import from a function scope.
(ノ≧ڡ≦) Teehee~!

The react-select module cannot find react

React-select cannot find React:
TypeError: React is undefined1 react-select.js:826:4
React-select.js is getting react through
var React = (window.React);
It lookes like i have to include React in the html to make this work, but i would like to avoid this. Is there something i am missing?
(using node)
Let me guess, you require dist/react-select.js. This script is used for browser environment. Try to require node environment script, which described in package.json. Or if you use npm install react-select it enough to call require('react-select');
We need some more clarification here, "using node" - are you rendering on node server?
If you are rendering in the client/browser, var React = (window.React); can possibly be called before window.React is available...
I recommend using commonJs pattern ie: var React = require('React');
I hope my answer will solve some of your issues with React. To start off, React is not the most 'noob' frendily 'View'(MVC).
I personally believe that HTML should only handle any Javascript. Let's separate the concerns into two.
|-- index.html
|-- app.js
Now, we have two files with two separate concerns. I do agree that the proper way to 'requiring' <== current way || 'import' new ES6way (AS of Release of Node 6) but for the simplicity sake, let's use CDNs.
Add these script tags
<script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js'> </script>
"Keep clam =*= solve bugs"

Three on node.js with ColladaLoarder

I know now how use JsonLoader in three.js for node.js.
But I have see, in the folder examples (three\examples\js\loaders) of node module an other loader whose is ColladaLoader.
I have try to execute this loader, but he isn't in the core folder of module.
I obtain an error: "ColladaLoader is not a function"
I have try to make a require to this file, but I obtain an error even I make a require to three module : "Three is not defined"
How can I use this ColladaLoader in node.js?
Thank You
var fs = require('fs');
var THREE = require("three");
eval(fs.readFileSync("bower_components/three.js/examples/js/loaders/ColladaLoader.js")+"");
First you load three.js, ensure you set it to a var with the uppercase name "THREE". Then you load the ColladaLoader - feels quite dirty.
A more beautiful solution would encapsule ColladaLoader.js to a node module.
If "ColladaLoader is not a function", then you did not reference to the ColladaLoader.js file.
Make sure to add <script src="js/loaders/ColladaLoader.js"></script> (or where ever your src is located) in your <head> or <body> somewhere before calling the ColladaLoader() function.

How to use npm module in Meteor client?

I'm thoroughly confused on how to use an npm module in Meteor client code.
I understand modules like fs would only work server-side, but in this case I'd like to use a simple text module like this for displaying pretty dates:
https://github.com/ecto/node-timeago
I've tried installing the module under /public/node_modules,
and it works great on the server-side following these instructions from SO: (
How do we or can we use node modules via npm with Meteor?)
Meteor.startup(function () {
var require = __meteor_bootstrap__.require
var timeago = require('timeago')
console.log(timeago(new Date()))
...
However it doesn't work in the client-side code:
if (Meteor.is_client) {
var require = __meteor_bootstrap__.require
var timeago = require('timeago')
console.log(timeago(new Date()))
...
Uncaught ReferenceError: __meteor_bootstrap__ is not defined"
Server-side is sort of useless for me in this case, as I'm trying to render text on the client.
I don't believe you need to use the server side version. Use the npm stuff for server side only and btw, put it in your /public/ as well. Who knows maybe you can call it once it is in your /public/, try it. Or try this.
Use something like the jquery timeago.js
Put it in /client/ or something like /client/js
Create a /client/helpers.js or some such.
Use a handlebars helper.
Handlebars.registerHelper('date', function(date) {
if(date) {
dateObj = new Date(date);
return $.timeago(dateObj);
}
return 'a long long time ago in a galaxy far away';
});
Example of calling 'date' handlebars helper function from template.
{{ date created }}
Where date is the handebars helper and created is the date coming out of the meteor/mongo collection.
See the github Britto project. That is where I got this code snippet and used it in a chat room app I wrote. Works fine.
There are a couple of others floating out there. Go to madewith.meteor.com and peruse the source of some of the projects.

Resources