I trying to use Tesserract.js https://github.com/naptha/tesseract.js#documentation with Vue.js which uses Vite as bundler.
My problem is that I get this error:
Cannot read properties of undefined (reading 'TESS_ENV')
This error happens inside:
module.exports = {
...defaultOptions,
workerPath: (typeof process !== 'undefined' && process.env.TESS_ENV === 'development')
? resolveURL(`/dist/worker.dev.js?nocache=${Math.random().toString(36).slice(3)}`)
: `https://unpkg.com/tesseract.js#v${version}/dist/worker.min.js`,
/*
* If browser doesn't support WebAssembly,
* load ASM version instead
*/
corePath: `https://unpkg.com/tesseract.js-core#v${dependencies['tesseract.js-core'].substring(1)}/tesseract-core.${typeof WebAssembly === 'object' ? 'wasm' : 'asm'}.js`,
};
Well, in vite I need to use import.meta.env.MODE instead of process.env.TESS_ENV
I tried to change the tesseract.js code. I went inside:
node_modules -> tesseract -> src -> worker -> browser -> defaultOptions.js
And changed it to import.meta.env.MODE but for some reason the code does not get applied and it still displays me the old error.
How do I make this work?
I got it:
export default defineNuxtConfig({
vite: {
define: {
"process.env.TESS_ENV": process.env.ENV,
},
},
});
I need to defined it, now its not undefined anymore
Remember to use the correct prefixes for .env file used in Vite, Nuxt etc.
ex.:
Vite .env
//.env file
VITE_BASE_URL: 'example.com'
Nuxt3 .env
//.env file
NUXT_BASE_URL: 'example.com'
OR
define it straight inside defineNuxtConfig
Related
I am working on trying to integrate a chess engine + AI into a html / css / javascript project. When it is eventually compiled, it will need to run from a .zip file and can therefore not rely on too many dependencies. It isn't accessing a server, but just needs to be able to run on its own. The API I've settled on is "js-chess-engine" available at https://www.npmjs.com/package/js-chess-engine. I have it available in the directory I am using. Following the import steps on the website it gives, I have found that the ESM solution does not work, but the commonJS 'require()' does work when running just my script.js file by itself in the VS Code inbuilt console. However, when running it through the index.html file, I get many errors and none of the solutions that I have tried have worked.
Further, the way the export system has been implemented in js-chess-engine is really weird and
HTML (snippet):
...
<script src="./node_modules/js-chess-engine/dist/js-chess-engine.js"></script> <!-- Any variation of this I've tried doesn't seem to work, including getting id of it -->>
<script type="module" src="./script.js"></script> <!-- Using type="module" or not gives errors, sometimes different depending on which type of import I am using -->>
...
script.js:
const jsChessEngine = require("js-chess-engine");
const game = new jsChessEngine.Game();
console.log(jsChessEngine.aiMove(4));
Some of the errors I have gotten:
import jsChessEngine from "js-chess-engine"
const game = new jsChessEngine.Game();
console.log(jsChessEngine.aiMove(4));
Gives
Uncaught TypeError: Failed to resolve module specifier "js-chess-engine". Relative references must start with either "/", "./", or "../".
And
import jsChessEngine from "./node_modules/js-chess-engine/dist/js-chess-engine.js"
const game = new jsChessEngine.Game();
console.log(jsChessEngine.aiMove(4));
Gives
Uncaught SyntaxError: The requested module './node_modules/js-chess-engine/dist/js-chess-engine.js' does not provide an export named 'default'
And
const jsChessEngine = require("js-chess-engine");
const game = new jsChessEngine.Game();
console.log(jsChessEngine.aiMove(4));
... works perfectly fine in the native VS Code execution, but not when running on a localhost in the browser. It gives:
Uncaught ReferenceError: require is not defined
Note that using requirejs to fix this issue did not work to fix this issue.
For reference: the head of the js-chess-engine.js file for exports (the next few lines also are used for exporting):
!function(t, e) {
"object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define("js-chess-engine", [], e) : "object" == typeof exports ? exports["js-chess-engine"] = e() : t["js-chess-engine"] = e()
}
...
Is there a solution that means I do not need to rely on Node.js / anything that does not work in browsers / does not use require / no dependencies? Any alternate suggestions for using js-chess-engine without any dependencies would be appreciated.
I use graphql's dataloader in a project. Unfortunately, it breaks Webpack 5 because:
setImmediate is not defined
I see where the issue is coming from in their source code. I forked the repo, made a patch and added it to my package.json. But the file that import dataloader can't resolve the path. So I need to add a polyfill for this function.
I've tried to write this in my file:
if(typeof Window.prototype.setImmediate !== "function") {
Window.prototype.setImmediate = function() {
return false
};
}
But typescript claims that:
Property 'setImmediate' does not exist on type 'Window'
How to fix this?
I am building a custom web component using angular 8. I have noticed that Angular 8 doesn't have --single-build true, so i used the following code
(async function build() {
const files = [
"./dist/bundle/runtime-es2015.js",
"./dist/bundle/polyfills-es2015.js",
"./dist/bundle/styles-es2015.js",
"./dist/bundle/scripts.js",
"./dist/bundle/vendor-es2015.js",
"./dist/bundle/main-es2015.js"
];
await fs.ensureDir("elements");
await concat(files, "elements/bundle.js");
})();
I have excluded the ...-es5.js files. The following code works when i remove all scripts tags in the index.html file and use bundle.js but when i import the custom element in another project i get Uncaught TypeError: Cannot read property 'bind' of undefined from the following line :
*/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
/******/ jsonpArray.push = webpackJsonpCallback;
window["webpackJsonp"] returns a function instead of an array causing jsonpArray.push.bind(jsonpArray); to error. Came across ngx-build-plus, --single-bundle works but excludes the global styling only imports component scss, tried including --bundle-styles false and --keep-styles in the ng build, it didn't work.
How can i solve the following error Uncaught TypeError: Cannot read property 'bind' of undefined when i concat all files ? Take note i am sing angular webpack not custom webpack. 2nd how can i make ngx-build-plus render global scss ?
The following link Cannot read property 'bind' of undefined helped me a lot. To add jsonpFunction: "o3iv79tz90732goag" in angular 8 had to npm i #angular-builders/custom-webpack and create a webpack config file see below: see documentation for #angular-builders/custom-webpack
const webpack = require('webpack');
module.exports = {
output: {
jsonpFunction: 'wpJsonpBundle'
}
};
Then add the custom webpack config file to angular.json
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js"
},
....
After ng build, i then concatenate the files using the function in the question and can use the custom element in other angular projects.
I want to bundle the files into my production build only if it is not for DEBUG;
So I've use webpack.DefinePlugin and set the variable DEBUG === true.
Also config webpack.UglifyJsPlugin with default options
And in the js file, I do like this:
const A = DEBUG === true ? null : require('./some-debug.js');
//do things with A, for example
console.log(A)
I checked the final bundle file, A is replaced with null (so DefinePlugin is working fine), but the content of some-debug.js file is still in the bundle js.
Is it possible to let webpack not require the file?
ps:
I think I can use resolve.alias to resolve './some-debug.js' --> undefined. But I want to keep my webpack.config.js generic, dont' want to apply too many resolve.alias entries.
Thanks
It doesn't work with ternary operator.
let A;
if (DEBUG === true) {
A = require('./some-debug.js');
}
I'm trying to use WebPack to include "showdown". The problem is that showdown will require("fs") and check the return value. This makes WebPack throw an error.
It seems like it should be possible to configure Webpack to generate a shim so that call to require("fs") will return false.
Maybe one of these techniques might work: http://webpack.github.io/docs/shimming-modules.html
Here's the Showdown.js code. If I comment out this code inside the node modules directory, the problem is solved. However, there should be a better way.
//
// Automatic Extension Loading (node only):
//
if (typeof module !== 'undefind' && typeof exports !== 'undefined' && typeof require !== 'undefind') {
var fs = require('fs');
if (fs) {
// Search extensions folder
var extensions = fs.readdirSync((__dirname || '.')+'/extensions').filter(function(file){
return ~file.indexOf('.js');
}).map(function(file){
return file.replace(/\.js$/, '');
});
// Load extensions into Showdown namespace
Showdown.forEach(extensions, function(ext){
var name = stdExtName(ext);
Showdown.extensions[name] = require('./extensions/' + ext);
});
}
}
The solution was to switch to marked: https://www.npmjs.org/package/marked. The showdown library is problematic as far as modules go.
Add it to noParse e.g.
var config = {
output: {
path: buildPath,
filename: 'bundle.js'
},
module: {
noParse: [
/showdown/,
],
And webpack will assume it does not contain any useful calls to require 🌹
This issue should be fixed in showdown v >=1.0.0
This seems to be a Showdown problem rather than a webpack one. The code that requires fs is intended to only be run in a node environment. Unfortunately there are some typos in the code that checks if it's running in node (the first if statement in the code you posted, undefind instead of undefined).
There is an pull request that fixes this which hasn't been merged yet.
To be honest it looks like the Showdown library is no longer maintained (last commit November 2012) so you may be better off looking for an alternative if possible.