How to import another JS file in a Web Worker? - javascript

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.

Related

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

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));

How do I import another file in JS?

So I'm trying to import another file in JS and I keep getting errors. The main file is script.js and I'm trying to import CookieManager.js. I first tried using
var cookies = require('/CookieManager.js');
but that caused this error: Uncaught ReferenceError: require is not defined. I found out that this happends because require is only supported by Node.js and therefore is causes an error when trying to run it in a browser. I then tried using
import {getCookie} from "../CookieManager";
and set it as an export function which caused this:
Uncaught SyntaxError: Cannot use import statement outside a module
. To fix that, I changed the type of the file from text/javascript to module in HTML. This happened: net::ERR_ABORTED 404 (Not Found). Finally, I tried using
JQuery (`$.getScript('/CookieManager.js', function()`)
but that also resulted in an error:
jquery.min.js:2 GET http://localhost:63342/CookieManager.js?_=1591679474637 404 (Not Found)```
Here is the directory structure:
├───HomePage
│ ├index.html
│ ├style.css
│ ├script.js
├CookieManager.js
Try:
In package.json add:
{"type": "module"}
Then in CookieManager.js:
export function GetCookie() { // your code to import}
Then script.js:
import { GetCookie } from '../CookieManager.js';

Trying to require or import a npm installed module inside a vuepress component

I have 'npm install -S tabletop' into my vuepress site and I am struggling to either import or require the tabletop module.
I know next to nothing about webpack nor the internals of vuepress (this is nmy first vuepress project)
Building a static website for a friend but planning to use a google spreadsheet to hold current work opportunities and suck the line entries using tabletop.js (https://www.npmjs.com/package/tabletop) into a JSON then filter and loop through to present in a vuepress loop
However, I've failed at step one of this process ... using tabletop.js inside a vuepress container's tag
Hi all, I'm new to vuepress and webpack and I'm getting a headache over trying to use a javascript library. I'm familiar with javascript and writing my own scripts and also loading javascript libraries in raw html websites. But I've really got stuck trying to figure out where the relative path for a require statement should be
I've tried both npm installing and also inserting into the config.js HEAD (which appears in devtools) options 1 and/or 2 below
install tabletop.js with
npm install -S tabletop
2.add link to config.js' HEAD
module.exports = {
title: 'Starlife Company Services Ltd',
description: 'Cleaning and Security services across the South East',
head: [
['link', { type: 'text/javscript', src: 'https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.5.1/tabletop.min.js' }]
]
}
add a require in tags in component
<template>
....
</template>
<script>
export default {
name: "cleaning-cta"
};
console.log("script started from inside joblist.vue")
import as sheet from 'tabletop'
var recruitment = "https://docs.google.com/spreadsheets/d/1M7glQxJb31B3lQyKNqum5o-0eDAgKI54VBPUAJomIFM/pubhtml" ;
console.log(recruitment);
var tabletop = sheet.init({
key: '1M7glQxJb31B3lQyKNqum5o-0eDAgKI54VBPUAJomIFM',
callback: showInfo
})
</script>
I've tried various combinations of
import 'tabletop'
Tabletop.init(...)
-or-
require('tabletop')
import as from 'tabletop'
I've tried various relative pathways
'tabletop'
'./tabletop'
'../../tabletop'
'../../node_modules/tabletop'
without no avail all with either a require or an import or a HEAD inserted sript tag
without a path I get
vue.runtime.esm.js?4bfb:619 [Vue warn]: Failed to resolve async component: function () {
return Promise.all(/*! import() */[__webpack_require__.e(20), __webpack_require__.e(29)]).then(__webpack_require__.bind(null, /*! ./src/.vuepress/components/joblist */ "./src/.vuepress/components/joblist.vue"));
}
Reason: ReferenceError: Tabletop is not defined
with a relative path I get ...
client?cae4:159 ./src/.vuepress/components/joblist.vue?vue&type=script&lang=js& (./node_modules/cache-loader/dist/cjs.js??ref--3-0!/usr/local/lib/node_modules/vuepress/node_modules/babel-loader/lib??ref--3-1!./node_modules/cache-loader/dist/cjs.js??ref--0-0!/usr/local/lib/node_modules/vuepress/node_modules/vue-loader/lib??vue-loader-options!./src/.vuepress/components/joblist.vue?vue&type=script&lang=js&)
Module not found: Error: Can't resolve '../../tabletop' in '/home/pi/GitHub/starlife-website/src/.vuepress/components'
errors # client?cae4:159
(anonymous) # socket.js?e29c:47
sock.onmessage # SockJSClient.js?0a33:58
EventTarget.dispatchEvent # sockjs.js?fb87:170
(anonymous) # sockjs.js?fb87:887
SockJS._transportMessage # sockjs.js?fb87:885
EventEmitter.emit # sockjs.js?fb87:86
WebSocketTransport.ws.onmessage # sockjs.js?fb87:2961
vue.runtime.esm.js?4bfb:619 [Vue warn]: Failed to resolve async component: function () {
return __webpack_require__.e(/*! import() */ 20).then(__webpack_require__.bind(null, /*! ./src/.vuepress/components/joblist */ "./src/.vuepress/components/joblist.vue"));
}
Reason: Error: Cannot find module '../../tabletop'
Every variation of the path both for import or require seems to end up in the same two errors:
Error: Cannot find module '../../tabletop'
-or-
Reason: ReferenceError: Tabletop is not defined
After several hours I'm lost ... spent hours googling for examples none of which are based within vuepress and none have been helpful
With Insuffiicent knowledge to poke through webpack, and running out of alternatives my project has hit a wall and I cannot see my way around.
Any ideas are much appreciated
Current state of project can be found at
https://github.com/kingdom-values-clients/starlife-website/tree/345d55eed65f110626a9e4d3bcadae1efcca0cbc
See above and also in thes commit
https://github.com/kingdom-values-clients/starlife-website/tree/345d55eed65f110626a9e4d3bcadae1efcca0cbc
Error: Cannot find module '../../tabletop'
-or-
Reason: ReferenceError: Tabletop is not defined
I know I'm probably doing something dumb here but cannot figure it out nor can I find any help for anything remotely like this inside a vuepress component.

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

Error with ffi module node.js Uncaught Error: Dynamic Linking Error: Win32 error 193

I want to call a function, which is written in "C" DLL, from node.js JavaScript. I am using "ffi" module in node.js and electron. The function which I want to call is "int FDColor_GetSWVersion(char* softwareVersion)". I am using the below code:
var libm = ffi.Library(__dirname + "\\viewmodels\\FDColor.dll", {
'FDColor_GetSWVersion': [ 'int', ['string' ] ]
});
But I am getting the error:
Uncaught Error: Dynamic Linking Error: Win32 error 193
It looks like that error means you have a 32/64 bit mismatch. You need to build the dll to match the loading process.
I chose the 64-bit DLL and loaded it successfully

Categories

Resources