what's the different between ///<reference path="..."/> and import statement - reactjs

at first when I import react, the typescript compiler console 'can not find module react',then I add /// , and the problem fixed.
but I just found if I remove the reference comment, there is no error.
this is my code:
/**
* Created by huagu on 2015/12/21.
*/
import * as ReactDOM from "react-dom";
import * as React from "react";
import FloatButton from "./FloatButton";
window.onload = function (event:Event) {
var bd = document.querySelector('#bd');
var style:__React.CSSProperties = {
width:'80px',
height:'40px',
background:'blue',
position:'absolute',
top:'100px',
left:'10px'
}
var str:__React.CSSProperties = '';
var num:number = '';
var c = <span style={{fontSize:'14px'}}>button</span>
var props = {
content:c,
click:function(){
console.log("FloatButton clicked");
},
style:style,
allowSeriesClick:false,
}
ReactDOM.render(<FloatButton {...props}></FloatButton>, bd);
}
so, my problem is whether reference comment is necessary?I don't add reference comment, but there is no error reference __React.CSSProperties, it was declare in react.d.ts. if it's not necessary, why there is no error with "var str:__React.CSSProperties = ''; "?

///<reference> is the equivalent of saying "Just trust me that this will have run before my code", which is often something you can safely assume. It's intended for IDEs, and since it's a comment, does not affect code execution at all.
import modulename ... uses either commonjs or requirejs to actually retrieve the specified module before running the proceeding code.
If you have a dependency-management system that works with the module you need, it's preferred to use that instead of the former solution; that way, there is no risk of trying to access a module before it's loaded (even if 99% of uses aren't even remotely possible for the code to see before it has loaded)

Related

process is undefined in React

I am building a simple React app that generates a QR code from data. I am interested in inspecting the memory usage when the QR code is generated. I am using the built process.memoryUsage() function but the app throws and exception
Uncaught TypeError: process__WEBPACK_IMPORTED_MODULE_1__.process is undefined
I have tested some different solution, i tried to rollback the react script version to "4.0.3" i tried to download the npm polyfill webpack but there is no success.
I am currently using these imports
import React, { useState, useEffect } from 'react';
import process from 'process';
import './App.css';
const QRCode = require('qrcode');
The function looks like this
let stringData = JSON.stringify(qrData);
console.log("Number of chars in data" + " " + stringData.length);
QRCode.toDataURL(stringData, function (err, url) {
if(err) return console.log("error occured")
//window.location.href = url;
})
const used = process.memoryUsage();
for (let key in used) {
console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
}
process is a Node.js API and is not available in the browser where your React app is running, which is why you see that error. If there is an available global process object, it is being polyfilled by something in your build tools, and will not have the memoryUsage method.
There is no equivalent API for the browser, but some related APIs do exist. Note that this is an evolving space and some are non-standard, so be sure to read both the spec and documentation before considering any usage:
Device Memory API (MDN)
Performance.memory (MDN)
You are using a built in nodejs package in a react app. Node executes on the server and has access to system level resources. React runs in the browser and does not. See this article for some tips measuring performance in React.

Import React statement syntax error creating a problem

I'm getting this error in an index.js file. I'm trying to make a simple react, javascript project using an api as well.
/*
import React from 'react'; // this enables jsx
^^^^^^
SyntaxError: Cannot use import statement outside a module
*/
My code looks like this:
/*import React from 'react'; // this enables jsx
import ReactDOM from '...react-dom'; // this allows us to attach the APP
import {
BrowserRouter as Router,
Route,
Link,
Switch
} from 'react-router-dom'; // this allows front end routing
import Home from './Home';
import Login from './Login';
import Activities from './Activities';
import MyRoutines from './MyRoutines';
import Register from './Register';
import Routines from './Routines';
const PORT = 3000;
const express = require('express');
const { client } = require('./db/client');
const server = express();
function App() {
*/
Method 1
A lot of interfaces still do not understand ES6 Javascript syntax/features, hence there is a need for Es6 to be compiled to ES5 whenever it is used in any file or project. The possible reasons for the SyntaxError: Cannot use import statement outside a module error is you are trying to run the file independently, you are yet to install and set up an Es6 compiler such as Babel or the path of the file in your runscript is wrong/not the compiled file. If you will want to continue without a compiler the best possible solution is to use ES5 syntax which in your case would be var react = require('react'); this can later be updated as appropriate or better still setup your compiler and ensure your file/project is compiled before running and also ensure your run script is running the compiled file usually named dist, build or whatever you named it and the path to the compiled file in your runscript is correct.
Method 2
Add "type": "module" to your package.json
{
// ...
"type": "module",
// ...
}
Note: When using modules, if you get ReferenceError: require is not defined, you'll need to use the import syntax instead of require.
Method 3
Update node.

CommonJS require vs. ES6 import discrepancy

So, I am new to React. Apologies if I am missing something obvious, I'm wrestling with a weird issue with my ES6 imports.
I'm using the #typeform/embed module (0.12.1), which oddly links to a GitHub repo on npm but that repo doesn't exist. So I haven't been able to look into potentially related issues.
Anyways, whenever I do the following:
import typeformEmbed from '#typeform/embed'
My text editor shows that the type of typeformEmbed is a string, and when I go to invoke a function on it, it is always undefined. Gives me the 'ole cannot invoke property X on undefined TypeError. It almost looks as if it is trying to import the README?
But, then I opened up my Node REPL and could write:
const typeformEmbed = require('#typeform/embed')
and it works like a charm.
Is there some discrepancy between the two that I am missing?
Edit: I know that this question is pretty text-heavy, let me know if there is crucial information that I'm missing. I should mention that I built this project with create-react-app.
import * as typeformEmbed from '#typeform/embed';
const popUpHandler = () => {
typeformEmbed.makePopup(
'https://admin.typeform.com/to/PlBzgL',
{
mode: 'drawer_left',
autoOpen: true,
autoClose: 3,
hideScrollbars: true,
onSubmit: function () {
console.log('Typeform successfully submitted')
}
}
)}
Should work for you

Play 2.5.3 ScriptException: TypeError: Cannot call undefined in <eval> at line number 1

I managed to download and run successfully the project here but then it broke after upgrading to Play 2.5.3. Any help? The error is on the last instruction
package controllers
import javax.inject._
import play.api._
import play.api.http._
import play.api.mvc._
import play.twirl.api.Html
import java.io.FileReader
import javax.script.ScriptEngineManager
#Singleton
class HomeController #Inject()(webJarAssets: WebJarAssets) extends Controller {
/**
* Create an Action to render an HTML page with a welcome message.
* The configuration in the `routes` file means that this method
* will be called when the application receives a `GET` request with
* a path of `/`.
*/
def index2 = Action {
Ok(views.html.index("Your new application is ready.",webJarAssets))
}
def index = Action {
// Pass 'null' to force the correct class loader. Without passing any param,
// the "nashorn" JavaScript engine is not found by the `ScriptEngineManager`.
//
// See: https://github.com/playframework/playframework/issues/2532
val engine = new ScriptEngineManager(null).getEngineByName("nashorn")
if (engine == null) {
BadRequest("Nashorn script engine not found. Are you using JDK 8?")
} else {
// React expects `window` or `global` to exist. Create a `global` pointing
// to Nashorn's context to give React a place to define its global
// namespace.
engine.eval("var global = this;")
// Define `console.log`, etc. to send messages to Nashorn's global `print`
// function so the messages are written to standard out.
engine.eval("var console = {error: print, log: print, warn: print};")
// Evaluate React and the application code.
engine.eval(new FileReader("target/web/web-modules/main/webjars/lib/react/react-with-addons.js"))
engine.eval(new FileReader("target/web/public/main/javascripts/components/App.js"))
Ok(views.html.main("React on Play",webJarAssets) {
play.twirl.api.Html(engine.eval("React.renderToString(React.createElement(App));").toString)
})
}
}
}

Test if an angularjs module is already created

I would like to test if a module is already created. Is it possible to check it with simple code like shown below?
if(angular.module('myApp') == undefined){
angular.module('myApp', ['ngRoute']);
}
No, it's not that easy. If angular.module is called with a single argument - the name of the module - it always throws an Error unless module is already there (source):
if (!requires) {
throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
"the module name or forgot to load it. If registering a module ensure that you " +
"specify the dependencies as the second argument.", name);
}
The point is mostly the same as with import clauses in other languages: if you do import a module (most probably as a dependency of another) and it's not there yet, it's a serious error - a show-stopper of a sort, hence an Error (and not just returning null or something).
And there's no easy way to access modules' list: it's stored in a variable local to moduleLoader. So one possible approach to solve this is wrap the check in try-catch:
function isModuleRegistered(moduleName) {
var isThere = true;
try {
angular.module(moduleName);
}
catch {
isThere = false;
}
return isThere;
}
Still I have to say if there's a need for such trick, it's a code smell. Angular has a nice (not perfect, but nice) dependency injection system, and it's not that hard to couple it with different loaders (like RequireJS, for example). If you need to manually check whether or not a module is there yet, most probably there's a deficiency out there waiting to bite you back. )
The only exception I can think about is a system that might work with different implementations of a single interface - and needs to check which one is supplied; but then again, that's easier to solve on a configuration level.
More better way can be with try catch block
try {
var myApp= angular.module("myApp") ;
}
catch(err)
{
angular.module('myApp', ['ngRoute']);
}
The following worked for me - then if the file got inserted twice into the main index.html file - the angular module would only be created once.
var myApp = myApp;
if (!myApp) {
myApp = angular.module('myApp', []);
}

Resources