Typescript module, require external node_modules - javascript

I need to use a simple node_module inside a simple typescript file, but it seems that the compiler doesn't want to get it.
Here's my simple ts file :
import glob = require('glob');
console.log(glob);
And I've got this error :
[13:51:11] Compiling TypeScript files using tsc version 1.5.0
[13:51:12] [tsc] > F:/SkeletonProject/boot/ts/Boot.ts(4,23): error TS2307: Cannot find external module 'glob'.
[13:51:12] Failed to compile TypeScript: Error: tsc command has exited with code:2
events.js:72
throw er; // Unhandled 'error' event
^
Error: Failed to compile: tsc command has exited with code:2
npm ERR! skeleton-typescript-name#0.0.1 start: `node compile && node ./boot/js/Boot.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the skeleton-typescript-name#0.0.1 start script.
However, when I use a simple declaration in this same script, it works :
var x = 0;
console.log(x); // prints 0 after typescript compilation
What am I doing wrong in this case ?
EDIT:
Here's my gulp file :
var gulp = require('gulp');
var typescript = require('gulp-tsc');
gulp.task('compileApp', ['compileBoot'], function () {
return gulp.src(['app/src/**/*.ts'])
.pipe(typescript())
.pipe(gulp.dest('app/dist/'))
});
gulp.task('compileBoot', function () {
return gulp.src(['boot/ts/*.ts'])
.pipe(typescript({
module:'commonjs'
}))
.pipe(gulp.dest('boot/js/'))
});
gulp.start('compileApp');
Thanks for advance
Thanks for advance

You are using the correct syntax:
import glob = require('glob');
But the error: Cannot find external module 'glob' is pointing out that you are using a special case.
By default, the compiler is looking for glob.ts, but in your case you are using a node module, not a module that you have written. For this reason, the glob module will need special treatment...
If glob is a plain JavaScript module, you can add a file named glob.d.ts with type information that described the module.
glob.d.ts
declare module "glob" {
export class Example {
doIt(): string;
}
}
app.ts
import glob = require('glob');
var x = new glob.Example();
Some Node modules already include the .d.ts in the package, in other cases you can grab it from Definitely Typed.

Here is the error with your code
import glob = require('glob');
Because in node.js import is not a reserved keyword. If you require any module in your application, you simply require it using the statement
var glob = require('glob');
Once done you can then use
console.log(glob);
To print the value of glob.Replacing import will hopefully do the job for you.

Related

Cannot run Parcel in my project (Parcel does not create dist with compiled file)

Please help me figure out the problem. I can not understand the essence of the error and how to fix it.
I initialize the project: npm init -y
Install Parcel: npm install --save-dev parcel
I create src directory with an index.html file.
When I run the npx parcel src/index.html command, I get an error:
Error: The filename, directory name, or volume label syntax is incorrect.
at Object.open (C:\Users\dell\OneDrive\Документи\Projects\Test\node_modules\lmdb\dist\index.cjs:1936:3)
at new LMDBCache (C:\Users\dell\OneDrive\Документи\Projects\Test\node_modules#parcel\cache\lib\LMDBCache.js:69:34)
at resolveOptions (C:\Users\dell\OneDrive\Документи\Projects\Test\node_modules#parcel\core\lib\resolveOptions.js:112:168)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Parcel._init (C:\Users\dell\OneDrive\Документи\Projects\Test\node_modules#parcel\core\lib\Parcel.js:218:27)
at async Parcel.watch (C:\Users\dell\OneDrive\Документи\Projects\Test\node_modules#parcel\core\lib\Parcel.js:315:7)
at async run (C:\Users\dell\OneDrive\Документи\Projects\Test\node_modules\parcel\lib\cli.js:349:9) {
code: 123 }
I had the same issue. I resolved it by changing the line at node_modules#parcel\core\lib\resolveOptions.js:112:168 to
let cache = (_initialOptions$cache = initialOptions.cache) !== null && _initialOptions$cache !== void 0 ? _initialOptions$cache : new (_cache().FSCache)(outputFS, cacheDir);
Basically, I removed the
outputFS instanceof _fs().NodeFS ? new (_cache().LMDBCache)(cacheDir) : part of that line. For some unknown reason, there seems to be a problem with LMDBCache and Parcel.
You're missing the build command from npx parcel src/index.html:
Update to:
npx parcel build src/index.html.

Uncaught ReferenceError: require is not defined (How to use a javascript library from the command line, or an html file)

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

esbuild cannot resolve the Node.js module 'events'

One of my dependencies contains the following code
var EventEmitter = require('events').EventEmitter;
exports.EventEmitter = EventEmitter;
exports.mixin = mixin;
function mixin(Constructor) {
for (var key in EventEmitter.prototype) {
Constructor.prototype[key] = EventEmitter.prototype[key];
}
}
I got the following error when trying to bundle everything into a file
$ npm run build
> gantt#0.0.0 build
> esbuild public/js/src/main.ts --bundle --minify --sourcemap --outfile=public/js/dest/bundled.js
> node_modules/sharedb/lib/emitter.js:1:27: error: Could not resolve "events" (use "--platform=node" when building for node)
1 │ var EventEmitter = require('events').EventEmitter;
╵ ~~~~~~~~
1 error
I am targeting browsers, so it's impractical to have --platform=node. I discovered this issue when searching around, but the offending line is in a dependency, so I cannot simply edit its source to replace the CommonJS module import with an ES module import.
How can I point esbuild to the implementation of events?

Error: A dynamic link library (DLL) initialization routine failed on electron but it's fine on node js

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

How to call Rust from JS and back?

I'm trying to adapt the game of life tutorial to call user-defined JS (instead of alert) from Rust:
index.js:
import * as wasm from "testing-wasm";
export const jsfunc = () => {
console.log("jsfunc called");
};
// Call Rust from JS. This function will call `jsfunc`, declared above.
wasm.rustfunc();
lib.rs:
mod utils;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen(module = "/www/index.js")]
extern "C" {
fn jsfunc();
}
#[wasm_bindgen]
pub fn rustfunc() {
// call JS
jsfunc();
}
wasm-pack build runs fine. But running the web project (npm run start) can't resolve the import anymore:
ERROR in ../pkg/snippets/testing-wasm-8ea926e8de57779d/www/index.js
Module not found: Error: Can't resolve 'testing-wasm' in '/Users/ischuetz/dev/ct-an/testing-wasm/pkg/snippets/testing-wasm-8ea926e8de57779d/www'
# ../pkg/snippets/testing-wasm-8ea926e8de57779d/www/index.js 1:0-37 7:0-13
# ../pkg/testing_wasm_bg.wasm
# ../pkg/testing_wasm.js
# ./index.js
# ./bootstrap.js
It works before introducing the circular dependency.
Any ideas? I also found import_js in wasm-bindgen but there's no direct call to Rust from JS.
in your Cargo.toml file add this:
[lib]
# if you want to integrate your rust code with javascript we use cdylib
crate-type=["cdylib"]
since you are using wasm-bindgen and wee_alloc and I assume it is already in your .toml file:
[dependencies]
wasm-bindgen="0.2.63"
wee_alloc="0.4.5"
When you build your code, pkg folder is created which includes glue javascript code wasm code. Now you need to get this pkg folder into the node modules. To do so, you have to link it to your javascript project's package.json:
"dependencies": {
// your path to ../pkg might be different
"rust_project": "file:../pkg",
},
Then in your javascript project directory, npm install. You will see that rust_project module is in your node_modules directory.
In your javascript file:
import rustfunc from "rust_project";
Now you can call your function

Categories

Resources