Web Components and dependencies isolation - javascript

Do web components really isolate dependencies inside each component?
I've imported two components in the same page and I get the following error:
Uncaught TypeError: JSON.stringify is not a function
Each of the components works fine when is alone in the page. Any ideas of how to fix this?
Thank you.

It does not isolate dependencies, and it does not run in a sandboxed JavaScript. However, you can use Web Component imports to make sure your dependencies are downloaded and run only once:
1) Add the import to each of your Web Components html:
<link rel="import" href="dependencies.html" />
2) Then dependencies.html should contain any scripts you need to be run only once:
<script type="text/javascript" src="mootools-1.2-core-nc.js"></script>
<script type="text/javascript" src="mootools-1.2-more.js"></script>
....
The browser will download dependencies.html only once on a page, and run it only once. It will simply ignore the other imports of this same file after the first time.
More info here:
http://www.html5rocks.com/en/tutorials/webcomponents/imports/
Update, if you have different dependencies for each webcomponent:
1) Add all the needed imports to each of your Web Components html:
<link rel="import" href="import-mootools-1.2-core-nc.html" />
<link rel="import" href="import-mootools-1.2-more.html" />
2) Then the import files should contain each one a single script you need to be run only once:
File import-mootools-1.2-core-nc.html contains only this line:
<script type="text/javascript" src="mootools-1.2-core-nc.js"></script>
File import-mootools-1.2-more.html contains only this line:
<script type="text/javascript" src="mootools-1.2-more.js"></script>
Note: If after that you still have problems, then it's not because you are including the dependencies more than once. See the Network tab at your console, and you will see it's downloaded only once. You probably have other issues there.

No, Web Components won't isolate external dependencies in general, if they deal with global objects or global context.
Your problem is that you are importing (at least) one library twice, and that library won't allow it.
Nothing related to Web Components anyway.
Update: also the polyfill webcomponents.js should not be imported twice.

Related

Unhandled Runtime Errorre: Referenceerror $ is not defined [jQuery in NextJs app]

There could be several reasons for a JavaScript "Unhandled Runtime Error" to occur. Some common causes include:
Syntax errors in the code: This can happen if there is a typo or incorrect syntax in the code.
Reference errors: This can happen if a variable or function is not defined before it is used.
Type errors: This can happen if a variable is used in a way that is not consistent with its data type.
Unhandled exceptions: This can happen if an exception is thrown and not caught by a try-catch block.
Unhandled promise rejection: This can happen if a promise is rejected and not handled with a .catch() block.
It's recommended to check the error message and the line number provided by the browser console and the code surrounding that line to understand the reason for the error.
What was my case
Reference error. What does reference error mean exactly?
Let's have a look then more details about of Reference error
A reference error in JavaScript occurs when a variable or function is used before it has been defined. This means that the JavaScript interpreter cannot find a reference to the variable or function in its current scope.
For example, if you have a line of code that uses a variable called "x" but you haven't defined "x" anywhere in your code, JavaScript will throw a reference error.
It's also possible to have a reference error if you try to access a property or method of an object that doesn't exist.
The error message associated with a reference error typically includes the name of the variable or function that caused the error, and the line number in the code where the error occurred.
For example console.log(x); where x is not defined anywhere will throw a reference error.
It's important to make sure that all variables and functions used in your code are properly defined and initialized before they are used in order to avoid reference errors.
In my project I ware using jQuery with the Nextjs app. both libraries' design patterns were not the same and for this reason, we can't use as like other js libraries(moment, date, etc.)
So, What's the way to use jQuery with the NextJs app?
Here are the details
Next.js is a JavaScript framework for building server-rendered React applications. To use jQuery with a Next.js app, you will need to include the jQuery library in your project. You can either include it as a local file or reference it from a Content Delivery Network (CDN).
Here is an example of how to include jQuery in your Next.js app using a CDN:
In your JSX file, add the following script tag to include the jQuery library:
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
In your JavaScript code, you can now use jQuery as you normally would. Alternatively, you can use npm package manager to install jQuery and import it in your .js file as:
npm install jquery
then in your .js file:
import $ from 'jquery'
If those solution doesn't solve your problem(Unhandled Runtime Errorre: Referenceerror $ is not defined), there is another method
Use Script from 'next/script'
import Script from 'next/script';
And now have a look at where we wrongly setup "next/script"
## strategy
<Script strategy="lazyOnload" src="./assets/js/jquery.min.js" />
<Script strategy="lazyOnload" src="./assets/js/popper.min.js" />
<Script strategy="lazyOnload" src="./assets/js/bootstrap.min.js" />
<Script strategy="lazyOnload" src="./assets/js/jquery.sticky-sidebar.min.js" />
<Script strategy="lazyOnload" src="./assets/js/slick.min.js" />
<Script strategy="lazyOnload" src="./assets/js/custom.js" />
Try to understand the meaning of "strategy" and use exactly what you need.
Next Script has a total of four strategies
"lazyOnload" | "afterInteractive" | "beforeInteractive" | "worker"
The default setup is afterInteractive but when we have to use "lazyOnload", "beforeInteractive" and "worker"?
At this point I also did the mistake.
but the solution is very simpler
https://nextjs.org/docs/basic-features/script
You can have a look at both Script setups and try to match what's the difference between them.
## strategy
<Script strategy="beforeInteractive" src="./assets/js/jquery.min.js" />
<Script strategy="beforeInteractive" src="./assets/js/popper.min.js" />
<Script strategy="beforeInteractive" src="./assets/js/bootstrap.min.js" />
<Script strategy="beforeInteractive" src="./assets/js/jquery.sticky-sidebar.min.js" />
<Script strategy="beforeInteractive" src="./assets/js/slick.min.js" />
<Script strategy="lazyOnload" src="./assets/js/custom.js" />
#Wish you, Hope your issue will fix...

StencilJS: How to compile a component production-ready (so it's simple to be used in projects)

A group of volunteers has created a single/multi-select component using StencilJS: https://github.com/NothingAG/adg-components
Now we want to hand it over to the client so they can use it in their project.
My expectation was that the final result could be made available as a single JavaScript file and be included by a website like this:
<script type="module" src="/build/adg-components.esm.js"></script>
<script nomodule src="/build/adg-components.js"></script>
<adg-combobox
id="hobbies"
name="hobbies"
label="Please select your hobbies"
optionslabel="Hobbies"
multi="true"
lang="de"
></adg-combobox>
But it turns out that the command npm run build creates a whole bunch of different files, and all need to be available:
We also included some translation feature, whose files need to be available, too:
My question is: is this just the way it is? Does the client to make all those files available so that the <script type="module" src="/build/adg-components.esm.js"></script> call can find them? Or did we misconfigure the compilation, or forgot about something important?
In a nutshell - yes, that's the way it is. So you need to distribute not just adg-components.esm.js but everything else in the folder as well. The Stencil docs explain this, but to summarize, the purpose is so that components are selectively lazy loaded. If you have a library with 100 components, the browser only needs to download the components that are actually used on the page, not all 100.

JS Hello Week "ReferenceError: HelloWeek is not defined"

I want to use this library : https://hello-week.vercel.app/
I'm having a hard time to understand how to use it. I know JS and I never used Typescript or Nodejs. I found the .js and .css of this library but it's seems not to work
"calendar.js:1 Uncaught ReferenceError: HelloWeek is not defined"
Can I included like a normal js file ?
Yes the installation guide is not really clear, here is how to get it done:
First of all this line is simply wrong
new Hello Week({
There should not be a space there, do this instead
new HelloWeek({
Also, you will need the language file. Ether host it in its particular directory hierarchy or use the langFolder option to specify where it is.
dist
-- langs
-- -- en.json
Finally, this dose not work when not in a server due to a CORS issue. Serve the files through a server and you will have it working.
You can find the basic usage in the Installation page of the docs. Just ensure to reference hello.week.min.js, hello.week.min.css and hello.week.theme.min.css. Typescript or Node.JS don't seem to be necessary.
Here is a quick HTML + JS example:
<link href="hello.week.min.css" rel="stylesheet" />
<link href="hello.week.theme.min.css" rel="stylesheet" />
<div class="calendar"></div>
<script type="text/javascript" src="hello.week.min.js"></script>
<script>
new HelloWeek({
selector: '.calendar'
});
</script>

Adding external javascript script to React

I'd like to include & run some js file in the React using Helmet component. Here is the simple code:
index.js:
import React from "react";
import ReactDOM from "react-dom";
import { Helmet } from "react-helmet";
import "./styles.css";
function App() {
console.log("op");
return (
<div className="App">
<Helmet>
<script src="hello.js" type="text/jsx" />
</Helmet>
<h1>Hellok CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
and ultra simple js script to include & run:
hello.js:
console.log("opl882...")
document.body.style.backgroundColor = "red";
But the script seems NOT to work! - i have no console output and/or background color changed. What's odd when I use the js code as an inline code like:
<Helmet>
<script type="text/javascript">
console.log("opl882..."); document.body.style.backgroundColor = "red"
</script>
</Helmet>
it works!
Why doesn't the external js file work?
I usually do not implement .js files in react using a script tag. Instead you should import it at the top like this (assuming './hello.js' is the route to the file):
import './hello.js'
That file must also be located inside the src folder.
I think the core issue you're probably seeing here is that hello.js is not accessible to the browser at the given URL. The src attribute in the <script> tag gives the URL for the browser to load the script from. Verify that you can directly access the script at the URL: it should just load as text in your browser to read if it's accessible.
The specifics of making a file directly accessible vary depending on your setup, but for a standard Create-React-App project (and a lot of others) there is a folder called public and you can put files you need to directly access by URL in there. To verify it's working, add your file there, then try to access it from the root of your app. If your app is running at localhost:3000 for instance, you can verify the file is accessible by navigating your browser to localhost:3000/hello.js. The file contents should appear in your browser as plain text. (Also, minor nitpick, I would use /hello.js as the src location, that feels like a less ambiguous URL to me.)
Once that's working, check out this StackOverflow over here to see about loading and running a vanilla JS file within React: Adding script tag to React/JSX .
In your case, you're already using Helmet, so I think the code you already posted is mostly good to work, but the answers in that link should help troubleshoot. Although I think you want to change the type to text/javascript or just omit it entirely.
Finally, the reason the in-line JS works but not the referenced file is why I think it's about your browser not being able to find/access hello.js. The in-line JS just runs as it is because the JS is baked in. But to run it from a src, it has to find the source first, so if it can't find it at the URL you've given, it won't run. As for the other answer by Bilal here, that would work too, but it's depending on some sort of webpack magic or something to see it's a Javascript file, then pack it in such a way so that it runs. Nothing wrong with that necessarily, but you're basically offloading the creation of the <script> tag to whatever process interprets the import. (Also, note that if you're able to do import './hello.js', then your hello.js file must live in your overall src folder, so it's not publicly accessible, which means the script src is invisible from the browser's POV.)
useEffect(()=>{require('./paywell.js')},[])

Adding Heap Analytics code in React Project

I am trying to add heap analytics script in my react project but it keeps throwing this error "'heap' is not defined". And I cannot compile the project due to this error.
As far as I know, heap wants their code to run in <head></head> tags. But I can't figure out how to make a code run inside <head></head> in react. The rest of the scripts like GTM and FB pixel code is running fine.
Any help is appreciated.
Just call it off:
window.heap.identify('random#myemail.com', 'email');
For some reason this isn't more clear on their website but if you check their docs here then you'll see that you just have to call window.heap.track() not just heap.track().
Also, you want the script as they mention in your index.html file at the bottom of the <head> element aka right before </head>
You should be able to include the heap script under head tag as below (Set right path to script in place of yourHeapScriptPath)
<script type="text/javascript" src="yourHeapScriptPath.js"></script>
If your're using webpack, you've got two options:
A) put your script in index.html and ask in your React-Scripts if the variables are defined
B) Put the scripts in your webpack entries, like the following:
const config = {
entry: {
app: './src/app.js',
vendors: './src/vendors.js'
}
};
See webpack-entries for more information.

Categories

Resources