Including an external js script in a React Component - reactjs

I have a react application, managed using react-scripts.
In my app i am using an external js script. The external script doesn't do any module exports.
The structure of the external script is as below (too big to include it in full).
var TradingView = {.... various functions }
At the end of the file:
if (window.TradingView && jQuery) {
jQuery.extend(window.TradingView, TradingView)
} else {
window.TradingView = TradingView
}
My goal is to create a simple react component using the external script, and call the function: TradingView.widget({...});
I have been searching online for ways to include an external script in a react component/ES6 style, and have tried various options: react-async-script-loader, and various webpack plugins: script-loader, imports-loader, ProvidePlugin etc. But i haven't been able to make it work.
The error i am getting after using the imports-loader or ProvidePlugin is:
1189:31 error 'jQuery' is not defined no-undef
1190:9 error 'jQuery' is not defined no-undef
In my webpack config, i have:
In the loaders section:
{
test: /tv\.exec\.js/,
loader: 'imports?jQuery=jquery,$=jquery,this=>window'
}
In the plugins section:
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
When i create a simple webpage (no react), and include the script, and call TradingView.widget(), the page just works fine.
The closest i could get help was to look at:
Managing jQuery plugin dependency in webpack
But it didn't work for me. I am quite new to the react, webpack ecosystem, so I am not sure what i am missing here.
Please let me know if you need any additional info.
Update: I tested the above, including the script in a simple react component, but not using the react-scripts this time, and directly using webpack configurations. I was simply able to import the external js in my component directly, and it worked. I was also able to use imports-loader plugin in webpack to expose jQuery, which also worked. So its possible that using react-scripts needs something else to make it work.

It looks like your external script is handling its "exports" by adding them as members of window. You can use the import keyword on a file that doesn't define exports like so:
import "modulename";
There's nothing special about that syntax except that it doesn't imply that any functions or variables will be made available via the import facility. The code in "modulename" that assigns members to .window will execute, which is the important thing.
For compiler complaints about accessing window.* globals, try assigning the variable you want to access to a local variable:
const jquery = window.jquery;
...or maybe...
const TradingView = window.TradingView;
Then you'll have the variable in scope, and it should be usable.

Related

Import a file as a string (or source asset) in Gatsby / React

I want to import .ts, .tsx, .js, and .jsx files into a react component and render them within a PrismJS highlighting block. For example, let's say I have a TypeScript file with functionA in it that I want to highlight in my actual website:
functionA.ts:
export function functionA() {
console.log("I am function A!");
}
I want to include this in a different component. The problem is, when I import it, I am obviously importing the webpack module version of it. My weak attempt at trying to get my function render in a react component looks like this:
MyComponent.tsx:
import * as React from "react"
import { functionA } from "./functionA"
export function MyComponent() {
return (
<>
<h1>Here is your code block:</h1>
<pre>
<code>
{functionA.toString()}
</code>
</pre>
</>
)
}
and what will actually render on the page where the code block is will look something like this:
Here is your code block:
WEBPACK__IMPORT.functionA() {
console.log("I am function A!")
}
I can't exactly remember what the .toString() function output looked like, but the point is it is NOT just the contents of the file how it appears in a code edit for example - it has been modulized by WebPack.
So, in a Gatsby project, how can i get these various code snippets to be imported directly as a string, purely as they are written, without WebPack enacting its import stuff on it? Is there a plugin or some way to tell Webpack to use the imported file as its asset/source module type? I know for MD or MDX files there is the gatsby-remark-embed-snippet, but I am building a component based HTML page and can't use MD or MDX files!
It's very late, and perhaps I just can't see the forest from the trees, I know there must be a way to do this...
You need to require the file using webpack's raw-loader, i.e:
const functionA = require("!!raw-loader!./functionA");
This works for create-react-app, as in the solution discussed here, and this works for Gatsby as well!
After using require on such a file, the file contents can be rendered in the component as:
<pre>{functionA.default.toString()}</pre>
It's then up to you to add syntax highlighting using a tool like prism or similar.
Note this solution will only work as long as Gatsby V3 continues to use WebPack v4, as raw-loader is deprecated in WebPack v5 and will be phased out for asset/source type modules.

Why do I have to use "require" instead of "import from" for an image in React?

I see that this answer suggests the syntax for importing images as shown below (commented out). In my case, it didn't work out (complaining there's no modules to find in that file) and I had to switch to the syntax that's currently active.
// import Author from "../assets/author.png";
var Author = require("../assets/author.png");
The difference I can imagine is that I'm using TypeScript (transpiling my TSX by awesome-typescript-loader and loading my PNG file-loader) and they seem to use JSX. But as far my understanding goes, it all transpiles to plain JS and require in the end.
Being a noob on React, I'm not sure what the reason of this discrepancy is but also I'm not sure what to google for to investigate myself.
This is more of a problem with typescript than webpack itself, you might need to declare modules on a declaration file.
Create a declarations.d.ts
Update your tsconfig.json
"include": [
"./declarations.d.ts",
],
Put this on that file:
declare module '*.png';
Error might be gone.
You can declare a module for your images like this:
declare module "*.png" {
const value: any;
export default value;
}
Then, you will be able to import your image like this:
import AuthorSrc from "../assets/author.png";
This is happening because webpack doesn't support image import out of the box. So you need to add a rule for that in the webpack config file. When you add a new rule, TypeScript doesn't automatically know that, so you need to declare a new module to resolve this. Without the module, you will be able to import images, but TypeScript will throw an error because you didn't tell to it is possible.
This issue has nothing to do with webpack or any bundler and is not quite a problem with typescript.
Typescript has stated that `require("path") is a way to include modules to the scope of your current module, whilst it can be also used to read some random files (such as json files, for example).
As Vincent and Playma256 specified, you can declare a module wildcard to match certain file types, so you can import it as an import statement. But you don't really need to do this. Typescript won't give you an error if you are trying to import a png or a json file (tslint might, but that depends on your configuration).
By the way, if your declaration is within the source folder of your project as defined in tsconfig.json, you don't need to include it as specified by Playma256.
I've created a sample project in node for you to test:
https://github.com/rodrigoelp/typescript-declare-files
I think you can solve this problem with Webpack&&typescript.The official webpage of webpack has introduced something about this in
https://webpack.js.org/guides/typescript/
And I have try this myself in
https://github.com/reactpersopnal/webpack-root/tree/feature/typescript
The reason is that you would like to use non-code assets with TypeScript, so we need to defer the type for these imports for webpack.
Your could simply add custom.d.ts.
declare module "*.jpg" {
const content: any;
export default content;
}

React & FuseBox alias settings - Absolute Paths

I am using React with FuseBox as bundler. The issue I am having at the moment is that aliasing isn't working so I can help deal with relative path hell.
My structure of the project:
stores folder has my MobX stores and an index.ts file that exports all the stores.
services has a bunch of service classes all exported in there respective files (no index.ts)
So in my fuse.ts I have:
alias: {
"services": "~/services",
"stores": "~/stores"
},
Then in my ui folder for example I am importing like so:
import AccountStore from "stores";
I get [ts] Cannot find module 'stores' error on that line at "stores".
Not sure have I got the alias section wrong? My homeDir in fuse.ts is set to "src/". I don't have any paths or baseUrl set in tsconfig like I did have when we were using webpack to setup absolute paths. Not sure if those are needed again or if it is something I am doing wrong with alias.
Any tips would be great :)
I have looked at the alias documentation on the fusebox site and followed it and tried a few different combinations but not getting any closer to it working. Would love some examples from people who have got this working.
Edit:
I have additionally done the following while trying to figure this out:
remove .fusebox folder
restarted vscode
have checked the bundle and it is adding a tilde there so fusebox must be recognising it?
will continue to add more things I try..
My solution to the problem I was having was to put the tsconfig.json file inside my src folder and the project/app inside ~.
Inside tsconfig.json i set baseUrl to root.
{
"compilerOptions": {
"baseUrl": ".",
// ...
}
}
This then allowed me to do absolute imports that would be the same across all files so it would be easy to reuse imports and quickly copy if needed.
import { service1, service2, service3 } from '~/services';
import { store1, store2 } from '~/stores';
The tilde usually represents home or base on a lot of systems so a few devs agreed it would be appropriate to use it in our folder structure. Though did have to remember to remove ~ from .gitignore if you have something that is autogenerated and its automatically in there.

Accessing a Browserify/Babel ES6 Module with ES5 Syntax

Context
I have an ES6/react-js file called ExternalComponent.react.jsx, with the following structure:
import React from 'react'
import Swipeable from 'react-swipeable'
const ExternalComponent = React.createClass({
//...
})
export default ExternalComponent
I have used browserify/babel to compile this file into its ES5 version (the new ES5 file is called my-external-component-in-ES5.js) using the following command:
browserify -t babelify --presets react MyExternalComponent.react.jsx -o my-external-component-in-ES5.js
The output of this file is quite large (>20,000 lines of javascript); however, it appears to wrap ExternalComponent in a large IIFE (might be wrong about this).
Problem
My goal is to access the class ExternalComponent from a pure ES5 context (in my development environment, I am unable to use ES6). I'm assuming this is going to involve one of the following:
Within ExternalComponent.react.jsx, somehow add ExternalComponent to the global namespace, so that when it compiles to ES5 I can just refer to ExternalComponent by its name.
Somehow access the ExternalComponent class which is buried in the massive my-external-component-in-ES5.js using ES5 syntax.
I'm not sure how to do either (1) or (2).
NOTE: In case anyone is wondering why I want to do this, it's because I'm trying to use the ExternalComponent within ClojureScript (which only has ES5 javascript interop; hence I have to figure out how to access ExternalComponent using only ES5 syntax!).
When you compile an ES6 module to ES5 with Browserify it converts the import syntax into CommonJS calls.
This:
import foo from './foobar';
Becomes:
var foo = require('./foobar');
You can access and use your class exactly as you would expect from your ES5 file, there's no need to clobber the global namespace. Just use the CommonJS functions.
var ExternalComponent = require('./my-external-component-in-ES5');
ReactDOM.render
<ExternalComponent />,
document.getElementById('app')
);
If you're trying to do this from ClojureScript, then I suggest creating a standalone browserify build that exposes your modules with global variables. You can use a tool like browserify-umdify.
// external-component.js
export default ExternalComponent
This will be compiled to a Javascript file that exposes externalComponent as a global variable on the window object.
Compile it to somewhere like resources/public/js/compiled/bundled-deps.js, then add it to your index.html with a script tag (above your cljs build).
Then you'll be able to reference your JS modules through the JS namespace.
(def external-component js/ExternalComponent)

How to make it possible to use Typescript with SystemJS and Angular?

I'm trying to make SystemJS work with Typescript, but they seem to conflict with each other.
How can I take advantage of the autoloading from System.js without it conflicting with keywords on Typescript? using import / require makes Typescript using it's own way for loading and referencing files, although it translates export as module.exports = ..., it doesn't do the same for import
Is it possible at all to achieve this or I'll have to wait for Typescript to support ES6 keywords?
TypeScript 1.5 adds support for compiling to ES5 SystemJS module syntax.
Author a class like:
export class Foo {}
Then compile with
tsc --module system foo.ts
The result will be an ES5 module using the SystemJS format.
In TypeScript, you would write the following import statement...
import dep = require('dep');
console.log(dep);
When you compile, you pass the module flag:
tsc --module commonjs app.ts
This tells TypeScript to target CommonJS style modules (it can also target AMD if needed - SystemJS supports both styles of syntax).
The output looks like this:
var dep = require('dep');
console.log(dep);
This output is analogous to the following example from the SystemJS documentation.
// library resource
var $ = require('jquery'); // -> /lib/jquery.js
// format detected automatically
console.log('loaded CommonJS');
If you need more help, you can ask a question and include specific examples that demonstrate the issue and we will be able to give more specific advice.
you can see here the way I did it with traceur instead of Typescript, but it should work pretty much the same with Typescript, I'll add ts as soon as I can play again with it.
NOTE:Is more of self-reminder or a playground than a proper seed
As Steve mentioned the strongest point of SystemJs is that you can use almost any module definition , the loader should detect the module format, I personally prefer to declare the modules as in
define([deps...],(deps..){
// ...
})
I find it to be like constructor injection pattern from other languages and frameworks and it always translates to the same Javascript, beacuse it is Javascript , beautified with class and arrow functions (+anotated with types the case Typescript).
Also choosing amd shown clearly asynchronous intentions, that would be honor anyway if you choose lets say ES6 module syntax, beacuse the code after the import sentence will only executed when the dependencies have finished loading. pretty much like the async keyword it feels a little too cryptic for the non initiated
BTW: and OutOFcontext: Cheers from SA / JHB to the amazing work of SystemJS dev Mr. Bedford

Resources