I tried to replicate the example found here: https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js/quick-start_onnxruntime-web-bundler:
import * as React from 'react';
import ort from 'onnxruntime-web'
import regeneratorRuntime from 'regenerator-runtime'
function App_F() {
// https://github.com/microsoft/onnxruntime-inference-examples/blob/main/js/quick-start_onnxruntime-web-bundler/main.js
const onnxFunct = async () => {
try {
// create a new session and load the specific model
// the model in this example contains a single MatMul node
// it has 2 inputs: 'a'(float32, 3x4) and 'b'(float32, 4x3)
// it has 1 output: 'c'(float32, 3x3)
const session = await ort.InferenceSession.create('../../assets/onnx/model.onnx');
//const dataA = Float32Array.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
//const dataB = Float32Array.from([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120])
//const tensorA = new ort.Tensor('float32', dataA, [3, 4])
//const tensorB = new ort.Tensor('float32', dataB, [4, 3])
// prepare feeds. use model input names as keys
//const feeds = { a: tensorA, b: tensorB }
// feed inputs and run
//const results = await session.run(feeds)
// read from results
//const dataC = results.c.data
//console.log(`data of result rensor 'c': ${dataC}`)
} catch (e) {
console.log(`failed to inference ONNX model: ${e}. `)
}
}
return (
<div className='container'>
<h1 className='heading'>
F
</h1>
</div>
);
}
export default App_F;
In webpack.config.js :
new CopyPlugin({
patterns: [
{
from: path.resolve(__dirname, "./node_modules/onnxruntime-web/dist/*.wasm"),
to: path.resolve(__dirname, "[name][ext]")
},
{
from: path.resolve(__dirname, "./src/assets/onnx"),
to: path.resolve(__dirname, "./dist/assets/onnx")
}
As suggested here: regeneratorRuntime is not defined in TypeScript run in web
I tried to convert "target": "ESNext" ---> "target": "es5" in tsconfig.json:
tsconfig.json :
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["dom", "es2015", "ESNext"],
"outDir": "dist",
//"jsx": "react",
"jsx": "react-jsx",
"baseUrl": "./src",
"paths": {
"#sections/*": ["app/sections/*"],
"#app/*": ["app/*"]
},
"strict": true,
"sourceMap": true,
"skipLibCheck": true,
"noImplicitAny": false,
"noImplicitThis": false,
"moduleResolution": "node",
"esModuleInterop": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"allowJs": true
},
"include": ["src/**/*"],
"exclude": [
"src/index.js",
"dist",
]
}
But I get this error message : regeneratorRuntime is not defined
How to solve the problem?
I solved the issue following the indications found here:Uncaught ReferenceError: regeneratorRuntime is not defined in React
I added in package.json :
"browserslist": [
"last 2 Chrome versions"
]
Now I get another error : failed to inference ONNX model: TypeError: Cannot read properties of undefined (reading 'InferenceSession') , but that's a different issue
Related
I use Node.js application and TS 4.8, and I updated package file-type, but now my project compilation fails with error
[1] const _fileType = /#PURE/ _interopRequireWildcard(require("file-type"));
[1] ^
[1]
[1] Error [ERR_REQUIRE_ESM]: require() of ES Module /home/victor/Desktop/alytics/node_modules/file-type/index.js from /home/victor/Desktop/alytics/dist/routes/index.js not supported.
[1] Instead change the require of /home/victor/Desktop/alytics/node_modules/file-type/index.js in /home/victor/Desktop/alytics/dist/routes/index.js to a dynamic import() which is available in all CommonJS modules.
There is my swc config:
`
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": false,
"decorators": true,
"dynamicImport": true
},
"target": "es2020",
"paths": {
"#routes/*": ["./src/routes/*"],
"#middlewares/*": ["./src/middlewares/*"]
},
"baseUrl": "."
},
"module": {
"type": "commonjs"
}
}
`
And there is my tsconfig:
`
{
"compilerOptions": {
"target": "es2020",
"module": "es2020",
"allowJs": true,
"removeComments": true,
"resolveJsonModule": true,
"typeRoots": ["./node_modules/#types"],
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"outDir": "dist",
"strict": true,
"lib": ["es2020"],
"baseUrl": ".",
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"moduleResolution": "Node",
"skipLibCheck": true,
"paths": {
"#routes/*": ["./src/routes/*"],
"#middlewares/*": ["./src/middlewares/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
`
Where I use file-type:
`
import KoaRouter from "#koa/router";
import { Context } from "koa";
import { logger } from "#middlewares/index.js";
import * as FileType from "file-type";
const router = new KoaRouter();
router.get("/", logger, (ctx: Context): void => {
ctx.body = { message: JSON.stringify(FileType) };
});
export default router;
`
As I understand, file-type package using only ESM import, but , after compilation this import convert to require(). I read about this issue in their repository, but this topic was closed as TS now support ESM.
How can I configure my ts.config to exclude this module to covert to require ??
Is there any way to solve this issue only using TS config?
I find the only solution - convert from commonjs - to ESM (change type: module, and add that to my package.json), but I don't want to update all my import adding .js at the end and I dont want to convert all my imports to ESM.
I am trying to implement encryption into my project using vuejs and typescript. I successfully implemented it in the .vue file, but when I try to write the encryption into a typescript class, the mocha test runs it, but when I try to compile and open it in the browser i get a javascript error in the console:
app.js:128620 Uncaught ReferenceError: require is not defined
at Object.crypto (app.js:128620)
at __webpack_require__ (app.js:20)
at Object../resources/ts/Classes/Model/Crypter.ts (app.js:125233)
at __webpack_require__ (app.js:20)
at Object../resources/ts/Controller/AuthController.ts (app.js:125924)
at __webpack_require__ (app.js:20)
at Object../node_modules/babel-loader/lib/index.js?!./node_modules/babel-
loader/lib/index.js!./node_modules/vue-
loader/lib/index.js?!./resources/js/Components/Includes/Login.vue?
vue&type=script&lang=js& (app.js:3308)
at __webpack_require__ (app.js:20)
at Module../resources/js/Components/Includes/Login.vue?
vue&type=script&lang=js& (app.js:124322)
at __webpack_require__ (app.js:20)
The marked line in the app.js is:
module.exports = require("crypto");
I already tried different importing 'strategies' in the typescript file like:
import * as crypto from "crypto";
import crypto from "crypto";
var crypto = require("crypto");
And also adding this in the webpack.mix.js
"node": {
fs: "empty",
crypto: true,
http: true,
https: true,
os: true,
vm: true,
stream: true,
path: true
},
but it didn't work.
The Crypter.ts
import crypto from "crypto";
export default class Crypter {
public constructor() {
}
public static publicEncrypt(data: JSON, publicKey: string): string{
let dataStr = JSON.stringify(data);
let dataB64 = Buffer.from(dataStr).toString("base64");
var buffer = Buffer.from(dataB64);
return crypto.publicEncrypt(publicKey, buffer).toString("base64");
}
}
The tsconfig.json
"compilerOptions": {
"allowUnreachableCode": false,
"allowUnusedLabels": true,
"alwaysStrict": true,
"charset": "utf8",
"declaration": true,
"declarationDir": "resources/ts/lib/types",
"declarationMap": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"importHelpers": true,
"lib": ["ES5", "ES6", "DOM", "DOM.Iterable", "ScriptHost"],
"locale": "en",
"module": "commonjs",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitUseStrict": false,
"noUnusedParameters": true,
"outDir": "public/js",
"baseUrl": "resources/",
"paths": {
"Base/*": [ "ts/*" ],
"#js/*": [ "js/*" ],
"#ts/*": [ "ts/*" ],
"Component/*": [ "ts/Components/*" ],
"Interface/*": [ "ts/Interfaces/*" ],
"Model/*": [ "ts/Model/*" ],
"Controller/*": [ "ts/Controller/*" ],
"Helper/*": [ "ts/Helper/*" ]
},
"pretty": true,
"sourceMap": true,
"target": "ES5",
"typeRoots": [
"node_modules/#types"
],
"downlevelIteration": true
},
"include": [
"resources/ts/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
],
"files": [
"./node_modules/#types/node/index.d.ts"
]
}
I expect the error to be resulting from wrong compiling or other misconfigurations.
You can't access nodejs crypto module in a web application. Node.js uses the same javascript syntax, but is not running in the browser.
You may need to install another crypto library such as crypto-js, that you can install using npm install crypto-js. There are probably plenty of other libraries that you can choose from (some ideas)
I have got a problem.
My TypeScript code is
import settings from './settings';
import YouTube from 'simple-youtube-api';
const youtube = new YouTube(settings.googleToken);
When I am compiling it with tsconfig.json:
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"lib": ["esnext"],
"outDir": "build",
"rootDir": "src",
"noImplicitUseStrict": true,
"resolveJsonModule": true,
"typeRoots": [
"node_modules/#types"
]
}
}
it ends up with this code:
Object.defineProperty(exports, "__esModule", { value: true });
const settings = require('./settings');
const simple_youtube_api_1 = require("simple-youtube-api");
const youtube = new simple_youtube_api_1.default(settings.googleToken);
How can I prevent the variable names changes and what should I change in tsconfig.json to remove the top line (Object.defineProperty(exports, "__esModule", { value: true });)?
Thanks in advance.
I am trying to run an example built in using typescript(using version 2.6) of async iterator through browser.
`
function* countAppleSales () {
var saleList = [3, 7, 5];
for (var i = 0; i < saleList.length; i++) {
yield saleList[i];
}
}
for(let val of countAppleSales())
console.log(val);
async function* asyncRandomNumbers() {
// This is a web service that returns a random number
const url = 'https://www.random.org/decimal-fractions/?num=1&dec=10&col=1&format=plain&rnd=new';
while (true) {
const response = await fetch(url);
const text = await response.text();
yield Number(text);
}
}
async function example() {
for await (const number of asyncRandomNumbers()) {
console.log(number);
if (number > 0.95) break;
}
}
example();
console.log('we are after await')
;`
above code is running fine in browser but am getting error cannot find name __values logged in console.log.
below is the type script configuration file am using:
{
"compilerOptions": {
"module": "es2015",
"types": [
"node"
],
// typeRoots option has been previously configured
"typeRoots": [
// add path to #types
"node_modules/#types"
],
"target": "es6",
"noImplicitAny": false,
"downlevelIteration": false,
"sourceMap": true,
"moduleResolution": "node",
"watch": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
//"noEmitHelpers": true,
"skipDefaultLibCheck": true,
"strictNullChecks": false,
"outDir": "tmp",
//"lib":["es2017","es2015","es2016","es2015.generator","esnext","dom","esnext.asynciterable"]
"lib": [ "es2017","dom","es2015.generator","es2015","es2015.iterable","esnext.asynciterable","esnext"]
},
"allowSyntheticDefaultImports":true,
"baseUrl": ".",
"paths": {
"lodash/*": [
"node_modules/#types/lodash-es/*"
]},
"awesomeTypescriptLoaderOptions": {
"useBabel": true,
"useCache": true
},
"include": [
"src",
"test"
],
"exclude": [
"node_modules",
"typings"
]
}
please can anybody help with this issue
this issue is resolved now, Issue is due to copy pasting typescript loader rules configuration twice in webpack configuration file. webpack error needs to be more specific though.
I am having a problem with TS where the tsc compiler is not picking up all the .ts/.js files in my lib directory. It's a very simple problem, not sure why it's happening. tsc is only picking up about 20% of the total number of files. Anybody know why it wouldn't pick up all of them in my lib directory?
I tried both 'classic' and 'node' for moduleResolution, same problem.
I have this tsconfig.json file:
{
"compilerOptions": {
"outFile": "dist/suman.js",
"declaration": true,
"baseUrl": ".",
"paths": {
},
"types": [
"node",
"async",
"lodash"
],
"typeRoots": [
"node_modules/#types"
],
"target": "es5",
"module": "system",
"moduleResolution": "classic",
"noImplicitAny": true,
"removeComments": true,
"allowUnreachableCode": true,
"lib": [
"es2015",
"es2016",
"es2017",
"dom"
]
},
"allowJs": true,
"compileOnSave": false,
"include": [
"lib/**/*"
],
"exclude": [
"test",
"node_modules",
"dist"
]
}
Using this command:
tsc --project tsconfig.json
I have the following output in
dist/suman.js
here is the output:
System.register("freeze-existing", [], function (exports_1, context_1) {
'use strict';
var __moduleName = context_1 && context_1.id;
return {
setters: [],
execute: function () {
}
};
});
// ..... more files...more files...
System.register("test-suite-methods/make-it", [], function (exports_12, context_12) {
'use strict';
var __moduleName = context_12 && context_12.id;
function handleBadOptions(opts) {
}
var domain, util, pragmatik, _, async, colors, rules, constants, incr, handleSetupComplete;
return {
setters: [],
execute: function () {
domain = require('domain');
util = require('util');
pragmatik = require('pragmatik');
_ = require('underscore');
async = require('async');
colors = require('colors/safe');
rules = require('../helpers/handle-varargs');
constants = require('../../config/suman-constants');
incr = require('../incrementer');
handleSetupComplete = require('../handle-setup-complete');
}
};
});