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';
Related
I'm new to javascript and programming in general. I would like to use this:
https://github.com/CesiumGS/gltf-pipeline
It's a tool to convert models into compressed formats.
This is my code:
const gltfPipeline = require("gltf-pipeline");
const fsExtra = require("fs-extra");
const processGltf = gltfPipeline.processGltf;
const gltf = fsExtra.readJsonSync("model.gltf");
const options = {
dracoOptions: {
compressionLevel: 10,
},
separateTextures: true,
};
processGltf(gltf, options).then(function (results) {
fsExtra.writeJsonSync("modeldraco.gltf", results.gltf);
console.log('done');
const separateResources = results.separateResources;
for (const relativePath in separateResources) {
if (separateResources.hasOwnProperty(relativePath)) {
const resource = separateResources[relativePath];
fsExtra.writeFileSync(relativePath, resource);
}
}
});
I copied this file, saved it as compress.js (because it rhymes) and I then ran it with
node compress.js - this is how I'd run a python file.
Error is: Cannot find module 'gltf-pipeline' which makes sense. So, I did:
node -r gltf-pipeline compress.js but I get the same error.
So, I moved to HTML/JS, where I made an index.html file and linked with a <script> tag compress.js and the gltf-pipeline index.js file. These are the errors:
index.js:3 Uncaught ReferenceError: module is not defined
at index.js:3
(anonymous) # index.js:3
compress.js:3 Uncaught ReferenceError: require is not defined
So how is this done? Either as a webpage or command line would be helpful.
This is my folder structure by the way, maybe that's the issue.
basefolder|
|- gltf-pipeline| library files in here
|- compress.js
|- index.html
|- model.gltf
gltf-pipeline works when used as a command line tool.
No.
You can't do that with Javascript.
JS is served to the client.
Whilst NodeJS runs on a server.
These are the differences between node and browser JS.
also for the module error try
npm install gltf-pipeline
Look at NPM to install Node Packages
Also take a look at the NodeJS Tutorial
I am trying to use a library from GitHub found here: https://github.com/cubing/jsss
the readMe has an example of how to use it:
// index.html
<script src="index.js" type="module" defer></script>
<select id="eventID">
<option value="333" selected>3x3x3</option>
<option value="444">4x4x4</option>
</select>
<button id="new-scramble">New scramble</button><br>
<div id="scramble-string"></div>
// index.js
import { randomScrambleStringForEvent } from "scrambles";
const eventSelect = document.querySelector("#eventID");
const scrambleStringElem = document.querySelector("#scramble-string");
async function newScramble() {
scrambleStringElem.textContent += " ⏳";
const scrambleString = await randomScrambleStringForEvent(eventSelect.value);
scrambleStringElem.textContent = scrambleString;
}
document.querySelector("#eventID").addEventListener("change", newScramble);
document.querySelector("#new-scramble").addEventListener("click", newScramble);
newScramble(); // Initial scramble
The repo is full of so many folders I am not sure which ones I need. I used the src to and put this in a folder called libs with but I have no idea if this is right. I tried using the whole repo and it still didn't work. Whenever I try following the "full example" that they have I get an error. As someone who has never done this before:
Where do I put the index.js file
what files do I need to copy to my project to make this work
Putting index.html and index.js in the root directory I get the error
'Uncaught TypeError: Failed to resolve module specifier "scrambles". Relative references must start with either "/", "./", or "../".'
When adding the correct directory to scrambles, I get the error
'Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.'
In short I have no idea what I am doing and no idea how to use this in my project, please help...
I'm trying to load a custom module in electron written in D with node_dlang package, which is fine with node, but it fails within electron.
the test with node, that runs just fine, goes like this:
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule != null);
assert(nativeModule.ultimate() == 42);
But when I went to use it within electron.js, through the preload script, it returns in an error.
the preload script goes like this:
const {
contextBridge,
ipcRenderer
} = require("electron");
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule.ultimate() == 42);
function pageLoaded()
{
// ...
}
window.addEventListener('DOMContentLoaded', pageLoaded);
the error when I attempt to load the module within electron application is:
A JavaScript error occured in the browser process
--------------------------- Uncaught Exception: Error: A dynamic link library (DLL) initialization routine failed.
\\?\C:\Users\001\Desktop\ele\module.node
at process.func [as dlopen] (VM70 asar_bundle.js:5)
at Object.Module._extensions..node (VM43 loader.js:1138)
at Object.func [as .node] (VM70 asar_bundle.js:5)
at Module.load (VM43 loader.js:935)
at Module._load (VM43 loader.js:776)
at Function.f._load (VM70 asar_bundle.js:5)
at Function.o._load (VM75 renderer_init.js:33)
at Module.require (VM43 loader.js:959)
at require (VM50 helpers.js:88)
at Object.<anonymous> (VM88 C:\Users\001\Desktop\ele\preload.js:6)
What's causing this and how do I fix this?
version
node version is: v14.17.0
electron.js: v13.1.1
both are 64-bit.
the module source code goes like this:
import std.stdio : stderr;
import node_dlang;
extern(C):
void atStart(napi_env env)
{
import std.stdio;
writeln ("Hello from D!");
}
int ultimate()
{
return 42;
}
mixin exportToJs! (ultimate, MainFunction!atStart);
it's compiled with dub command line. No arguments.
UPDATE 1 Do I need to rebuild this module? I found this but it didn't work for me either. I installed the electron-rebuild package by npm install --save-dev electron-rebuild and rebuild with .\node_modules\.bin\electron-rebuild.cmd -v 13.1.1 the command ran fine but I still got same error.
UPDATE 2: inside the console, I clicked in the javascript source code file link in the error message (from the exception) it points to this line of code, where there's this comment saying that:
no static exports found
what does that mean? is this related to the methods in D class? they're marked as public... not sure if related
Electron is a Windows-Application and therefore you need to remove output to std. Try to remove
import std.stdio : stderr;
and
import std.stdio;
writeln ("Hello from D!");
and retry import to Electron.
Please refer this (https://stackoverflow.com/a/74280836/9558119) post from me regarding same. Since it is electron build might be missing Visual C++ Build Environment: Visual Studio Build Tools
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.
I'm building my first electron desktop app and I'm getting a "cannot find module" error when I use require() in one file to import the other. Both files are in the same folder and there's no misspelling..
Here's the main file index.js
const app = require('electron')
const store = require('./datacontainer') //Here I import the other file
if(store.users.length==0) { // throws exception: store is not defined
...
}
and below is the imported file datacontainer.js
var exp = module.exports = {};
exp.users = [{user1},{user2},...];
...
However, when I run the app and look at the console, it throws the following exeption;
Uncaught Error: Cannot find module './datacontainer'
at Module._resolveFilename (module.js:543)
at Function.Module._resolveFilename (C:\mm_apps\report-viewer\node_modules\electron\dist\resources\electron.asar\common\reset-search-paths.js:35)
at Function.Module._load (module.js:473)
at Module.require (module.js:586)
at require (internal/module.js:11)
at index.js:10
What am I doing wrong or missing?
UPDATES:
In the index.html where the index.js is used, the error goes away if I reference the script like the following
<script>
require('./scripts/index')
</script>
but throws above error when referenced this way
<script src="./scripts/index.js"></script>
what gives?
When you do
<script src="./scripts/index.js"></script>
it looks for the file on the server.
Something like:
https://www.example.com/your-web-folder/scripts/index.js
Using Node.js's require resolves it according to the folder structure of your project.