I cannot find a way to use 'require' in html - javascript

I am now developing JS in html, but I'd got following error: Uncaught (in promise) ReferenceError: require is not defined.
The code is just simple subs = require("./subscriptions.json").subs;.
To solve this problem, I first tried module with import and got another errors.
<script type="module" src="subscribe.js"></script>
import { subs as subs } from "./subscriptions.json"; → Uncaught SyntaxError: Unexpected token '{'
import subs from "./subscriptions.json"; → Uncaught SyntaxError: Unexpected identifier
import * from "./subscriptions.json"; → Uncaught SyntaxError: Unexpected token '*'
import "./subscriptions.json"; → Uncaught SyntaxError: Unexpected string
This was same with "fs", a JS module, so I gave it up and tried to use require.js(2.3.6). But similarly, it threw errors.
<script data-main="subscribe.js" src="require.js"></script>
require(["./subscriptions.json"]); → Uncaught Error: Script error for "subscriptions.json"
require(["json!./subscriptions.json"]); → Uncaught Error: Script error for "json", needed by: json!subscriptions.json_unnormalized2 , Uncaught Error: Script error for "subscriptions.json" , Uncaught Error: Load timeout for modules: json!subscriptions.json_unnormalized2
require(["fs"]); → Uncaught Error: Script error for "fs"
What could be the problem in my code? When needed, I can share my full code.
ps. Actually I don't need to require or import something. I just want my independent JS files to share a json data. If there is a better way, share yours please. Thank you.

You can't use require in es6 modules. require is used in node.js and to read a json file in your browser side javascript you can use the fetch api in your javascript file and can get data from .json file and use it in HTML
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));

Related

Error in Vite Preview: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I'm facing this Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data error when using vite preview after vite build.
My vite.config.js:
import { defineConfig } from "vite";
import { svelte } from "#sveltejs/vite-plugin-svelte";
// https://vitejs.dev/config/
export default defineConfig({
base: "/weatherdatacollector_baku/",
plugins: [svelte()],
});
I'm not facing this issue when i use yarn dev.
How can i solve this issue
Try importing your JSON directly into you main.js file
import json from "./example.json";
console.log(json)
You should still be able to use async by referring whatever name you use to import.

Generating file throws error: Unexpected token '&'

In a Nuxt project the files are compiled strangely. This leads to error messages in the console and in my case affects the tracking.
The following Console.log error message comes up:
"Uncaught SyntaxError: Unexpected token '&'".
That is the part which occurs the console error:
<script data-n-head="1" data-hid="tealium" type="text/javascript">
(function(a,b,c,d){a='//tags.tiqcdn.com/utag/tr //etc... </script>
I expect: a='//tags.tiqcdn...
The relevant nuxt.config.js part
{
hid: `tealium
innerHTML: `
(function(a,b,c,d){a='//tags.tiqcdn.com/utag/../utag.js';b=document;c='script';d=b. createElement(c);d.src=a;d.type='text/java'+c;d.async=true;a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a);})();
`,
I use to build node v16.14.0 and npm 8.3.1.
What I have already tried:
I add nuxt-charset-module
https://www.npmjs.com/package/nuxt-charset-module to push the
<meta charset> to first of <head>.

How to import another JS file in a Web Worker?

I've got a WebWorker in which I want to use functions from another existing JavaScript file. I've tried different methods to import the JS file but so far none have worked. The file in question is in another directory, with relate path '../pkg/benchmark.js'.
Is there anyone who knows how to do this?
I've tried the following methods:
Method 1:
import * as myFile from '../pkg/benchmark.js';
which gives the errors:
Uncaught SyntaxError: Unexpected token *
Method 2:
import { myFunc1, myFunc2 } from '../pkg/benchmark.js';
gives the error:
Uncaught SyntaxError: Unexpected token {
Method 3:
Using importScripts()
importScripts('../pkg/benchmark.js');
gives the error:
worker_wasm.js:6 Uncaught DOMException: Failed to execute importScripts' on 'WorkerGlobalScope': The script at http://localhost:8080/pkg/benchmark.js' failed to load.
Method 4:
Using dynamic imports:
import('../pkg/benchmark.js')
.catch(e => console.error(e));
gives the error:
TypeError: Failed to fetch dynamically imported module: http://localhost:8080/pkg/benchmark.js
Since I'm using npm, it should be mentioned that in package.json I've defined the dependency
"dependencies": {
"benchmark": "file:../pkg"
}
so I normally don't have to specify the relative path, and instead just import 'benchmark' directly. This doesn't work either.
Method 5:
Finally, I've tried enabling the chrome flag
--enable-experimental-web-platform-features
and declare my worker as
new Worker("worker.js", { type: "module" });
which doesn't give any errors in the developer console but also doesn't run the imported functions.

requireJS, origin of the define statement

I'm working on a large project that uses Requirejs for dependency management, specifically the convention is for every file to have this pattern:
define(['dependency1', 'dependency2'], function (dependency1, dependency2) {
... some code ...
});
now I'm investigating a failure where some file is trying to require a dependency that no longer exists.
I'm getting this error from RequireJS:
GET https://some-location/some-file.js net::ERR_ABORTED
Uncaught Error: Script error for: some-file
http://requirejs.org/docs/errors.html#scripterror
at C (require.min.js:8)
at HTMLScriptElement.onScriptError (require.min.js:29)
at HTMLScriptElement.nrWrapper (...)
How can I know which file contains the faulty dependency?
Simply searching the project files is not good enough since it is a large project that spans across multiple code bases.
Is there a way to make RequireJS tell me who asked for it?
What version of requirejs are you using? I'm using 2.3.2 and the error output provide more info, take a look:
GET http://localhost:9090/requirejs/js/dependency1.js net::ERR_ABORTED
require.js:168 Uncaught Error: Script error for "home/dependency1",needed by: home/somefile
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:168)
at HTMLScriptElement.onScriptError (require.js:1735)
Please, note that the part that says needed by: home/somefile is telling us the file that is requiring the failed dependency. This is the small local test I did.
requirejs config
require.config(
{
paths: {
'home': './js'
},
callback: function() {
require(['home/somefile'], function(a) {
console.log(a);
});
}
}
);
./js/somefile.js
define(['home/dependency1'], function (dependency1) {
console.log(dependency1);
});
So, after getting the error Uncaught Error: Script error for "home/dependency1",needed by: home/somefile, we can say that the file requiring the failed dependency is PATH_TO_OUR_PROJECT/js/somefile.js. Remember that we need to pay attention to our paths in the require config.
You can play and test the Global requirejs.onError function but it won't give you more info than the regular requirejs output.
More info in Handling Errors from docs.
Hope it helps.
Following Castro Roy's answer i made a test to verify this is indeed issue of requireJS version.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Require Test</title>
<script data-main="main" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js"></script>
</head>
<body></body>
</html>
main.js
requirejs(['someFile'], function(someFile) {
console.log('main executing')
});
someFile.js
define(['someDependency'], function (someDependency) {
console.log('someFile executing')
});
and someDependency.js obviously missing.
Results:
using requireJs 2.1.20 (used in my project)
GET http://localhost:63342/playground-simple/someDependency.js net::ERR_ABORTED
Uncaught Error: Script error for: someDependency
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.min.js:1)
at HTMLScriptElement.onScriptError (require.min.js:1)
Then again using requireJs 2.3.2
GET http://localhost:63342/playground-simple/someDependency.js net::ERR_ABORTED
Uncaught Error: Script error for "someDependency", needed by: someFile
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:168)
at HTMLScriptElement.onScriptError (require.js:1735)
So clearly Yes.
This is an issue of version and not some unique behavior of my project and this information is given in the error message for later versions of require.
sadly i was not able to find any documentation for this change

Is this $parse:syntax error coming from my code or the angular library?

The error message says: "Syntax Error: Token 'false' is an unexpected token at column 8 of the expression [return] starting at [{4}]."
But the stacktrace in the browser console shows this:
Error: [$parse:syntax] http://errors.angularjs.org/1.4.8/$parse/syntax?p0=false&p1=is%20an%20unexpected%20token&p2=8&p3=returnNaNalse%3B&p4=false%3B
at Error (native)
at http://localhost:34574/libraries/angular/1.4.8/angular.min.js:6:416
at Object.s.throwError (http://localhost:34574/libraries/angular/1.4.8/angular.min.js:210:32)
at Object.s.ast (http://localhost:34574/libraries/angular/1.4.8/angular.min.js:202:296)
at Object.rd.compile (http://localhost:34574/libraries/angular/1.4.8/angular.min.js:211:406)
at gc.parse (http://localhost:34574/libraries/angular/1.4.8/angular.min.js:238:281)
at http://localhost:34574/libraries/angular/1.4.8/angular.min.js:117:338
at Object.compile (http://localhost:34574/libraries/angular/1.4.8/angular.min.js:254:1)
at Z (http://localhost:34574/libraries/angular/1.4.8/angular.min.js:65:275)
at O (http://localhost:34574/libraries/angular/1.4.8/angular.min.js:55:235)
The stacktrace only makes references to angular.min.js and I'm not sure if this is because the error is really in the library file or if the error is somewhere else and just showing up in the library. If it's the latter, how do I debug this?
$parse is responsible for transforming expressions like {{obj[0]}} to javascript objects/functions.
This is quite usual type of error. It comes from your html template. Some expression has wrong syntax. I.e.:
ng-class="{{'a' : a}" will give same type of error.

Categories

Resources