I am using Prisma (sqlite DB) with an Electron + Angular app
Everything works fine until I try to create a record
I'm getting this error in console few times repeated
Here is a part of my schema.prisma file:
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
binaryTargets = ["native","darwin","debian-openssl-1.1.x","linux-musl"]
}
I've tried using the same Prisma config with a scratch TS project and it works fine
When I've tried it with electron I was getting errors
As I understand it cannot find query engine binaries, but I don't know how to say to Electron where to get them from
Hi
I too had similar problem with prisma.
The issue is that the custom prisma client along with the downloaded binaries for the platform of use gets generated in node_modules/.prisma folder (default).
when webpack bundled the code, .prisma folder wasn't included with the generated app.asar package in node_modules folder and thus prisma client couldn't be loaded along with the binaries.
Solution
I changed the output path of the generated prisma client as per prisma doc
generator client {
provider = "prisma-client-js"
output = "../src/main/database/generated/client"
}
and included in my database.js file (located inside database folder) as follows
import { PrismaClient } from './generated/client';
As the downloaded binaries are also placed indside the output folder, there was no problem for prisma client in finding it.
I had the same issue when using electron-builder to build native binaries.
In my case I had to add .env file to the build block on package.json and change the output path as spc mentioned.
// package.json
{
...
"build": {
...
"files": [
...
".env"
],
...
}
}
// schema.prisma
generator client {
provider = "prisma-client-js"
output = "../electron/client"
binaryTargets = ["native"]
}
Related
I have a file that i need compulsory to make my application work,i am able to use the file in development by specifying fixed path var path = process.cwd() + '/src/app/components/task/Scripts'; and the file name after that,but after packaging the app i want to move the file i need in extraResources folder in system from where i will be able to use it let path = pathPackage.join(process.resourcesPath, 'extraResources');,i am using electron-forge maker to produce a production build exe,how ever there is no extraResources folder created after installing the exe,i am specifying it in package.json file
"build": {
"extraResources": [
"./extraResources/**"
]
},
Can someone provide a solution for it,i have tested all examples but none of them worked
As it mentions in the documention (actual options documented here), you can add files using the extraResource option of the packagerConfig configuration.
extraResource
extraResource: string | string[]
One or more files to be copied directly into the app's
Contents/Resources directory for macOS target platforms, and the
resources directory for other target platforms. The resources
directory can be referenced in the packaged app via the
process.resourcesPath value.
For example, in your package.json file:
{
"config": {
"forge": {
"packagerConfig": {
"extraResource": [
"./src/extraResources/file.txt",
"./src/extraResources/folder"
]
}
}
}
}
The files will be placed in the process.resourcesPath directory when running npm run package.
Since I can't use browser's pdf viewer in the network where the app is going to be used, I am testing a react-pdf package for loading PDF's with React.
I have made a component where I am sending a url of my PDF that I get from backend:
import React, { useState } from 'react';
import { Document, Page } from 'react-pdf';
const PDFViewer = ({url}) => {
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
function onDocumentLoadSuccess({ numPages }) {
setNumPages(numPages);
}
function onLoadError(error) {
console.log(error);
}
function onSourceError(error) {
console.log(error);
}
return (
<div>
<Document
file={window.location.origin + url}
onLoadSuccess={onDocumentLoadSuccess}
onLoadError={onLoadError}
onSourceError={onSourceError}
>
{[...Array(numPages).keys()].map((p) => (
<Page pageNumber={p + 1} />
))}
</Document>
</div>
);
};
export default PDFViewer;
But, on opening the PDFViewer I get an error
Error: Setting up fake worker failed: "Cannot read property 'WorkerMessageHandler' of undefined"
In documentation it says that you should set up service worker and that the recommended way is to do that with CDN:
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
But, I can't use CDN links for my project, and in the documentation it also says:
Create React App uses Webpack under the hood, but instructions for Webpack will not work. Standard instructions apply.
Standard (Browserify and others)
If you use Browserify or other bundling tools, you will have to make sure on your own that pdf.worker.js file from pdfjs-dist/build is copied to your project's output folder.
There are no instructions on how to do that with create-react-app. How can I set this up locally then?
Install pdfjs-dist
import { Document, Page, pdfjs } from "react-pdf";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
Reference: https://github.com/mozilla/pdf.js/issues/8305
found a more efficient way of including the worker
by including the library from the dependencies of react-pdf itself, this way you will never get a version mismatch like this The API version "2.3.45" does not match the Worker version "2.1.266"
if you install pdfjs-dist manually you will have to check react pdf dependency version on every build
import { Document, Page, pdfjs } from "react-pdf";
import pdfjsWorker from "react-pdf/node_modules/pdfjs-dist/build/pdf.worker.entry";
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
see similar error on pdfjs library : https://github.com/mozilla/pdf.js/issues/10997
hope it helps people
You can install worker loader module for webpack:
npm install worker-loader --save-dev
Then use it inline where you are going to work with a worker:
import SomeWorker from 'worker-loader?inline=true!../workers/some.worker'
const someWorker: Worker = new SomeWorker()
someWorker.postMessage(...)
I haven't tried this solution with react-pdf, but it might help.
You may need to add types for TypeScript if you are using it:
declare module 'worker-loader*' {
class SomeWorker extends Worker {
constructor()
}
export default SomeWorker
}
Just to add that in some .d.ts file in your project.
Install pdfjs-dist then use the webpack module:
import { pdfjs } from 'react-pdf'
import worker from 'pdfjs-dist/webpack'
pdfjs.GlobalWorkerOptions.workerSrc = worker
If your build process uses cli commands, (i.e. AWS buildspec), you can use this:
mkdir -p build && cp ./node_modules/pdfjs-dist/build/pdf.worker.js build
If you are in a corporate codebase environment and have little to no experience configuring WebPack, I wanted to share a little more info if (like me) you struggled with this for quite a long time.
My environment has several complicated WebPack config files (base, production, and development), and the resolution ended up being pretty simple but it escaped me for quite a while because I was unfamiliar with the complicated build process.
1) The Implementation
Quite simple, just as the docs recommend (I went with the minified file). Our React environment required me to use React-PDF#4.2.0, but there aren't any differences here.
import {Document, Page, pdfjs} from 'react-pdf'
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js'
Note: a previous solution recommended grabbing the source from the react-pdf node_modules folder, however, my codebase is setup to install dependencies separately somehow because when I npm install react-pdf, pdfjs-dist is also installed separately. Regardless, this method did not work for my codebase (importing the worker as a variable) due to the way the project is built. The import command acted like it couldn't find the proper named export inside a node_modules folder. It was top-level or nothing.
2) WebPack Config
Since I do not know WebPack at all, but found pretty easily that what I needed to do was take advantage of CopyWebpackPlugin, I searched through those existing dev and prod webpack config files, and found existing copy commands for JQuery and polyfill and added a new plugin to that array:
new CopyWebpackPlugin({from: 'node_modules/pdfjs-dist/build/pdf.worker.min.js})
I had to do this in multiples places in both config files as this large project has several entry point server files for the different services of the website.
3) Inserting Script Tag to HTML Head
This was the crucial part I was missing. There was a "ComponentFactory" file whose job it was to insert chunks of html in the <head> and tail of the html file. I wasn't used to something like this on small projects. So there, I simply copied what was already done for the jquery and polyfill, which included a string literal of the location of the assets folder the webpack was building out to. In my case, that was something like "assets/v1/". So the tag looked like this:
<script src=`${STATIC_ASSETS_URL}/pdf.worker.min.js` defer></script>
It works perfectly, however I am still getting the "Setting Up a Fake Worker" but immediately after that, it loaded it successfully in console and checking the dev tools, it was using the proper file. It's probably just a timing thing of the src set not running high enough in the code, but it was not effecting the outcome, so I let it go.
(Sidebar, if you also get the "TT unknown function" (paraphrasing) error, that can be ignored. It's just a font issue with whatever PDF you are loading and is just a warning, not an error.)
I was facing this issue once I had to use "react-pdf" from within a package.
It was solved by importing the worker conditionally into the code:
Conditional import:
export const getWorker = () => {
try {
return require('react-pdf/node_modules/pdfjs-dist/legacy/build/pdf.worker.entry.js')
} catch () {
return require('pdfjs-dist/legacy/build/pdf.worker.entry.js')
}
}
usage:
import { Document, Page, pdfjs } from 'react-pdf/dist/umd/entry.webpack'
pdfjs.GlobalWorkerOptions.workerSrc = getWorker()
I am new to React CRA (it is rewired as per doc in ant-design description for project setup) and facing issues in adding multiple entry points in webpack-config file.
I have 2 html files in public folder, index.html & stack.html.
-public
-index.html //runs on localhost:3000
-stack.html // runs on localhost:3000/stack.html
-src
-index.tsx
-stack.tsx
-config-overrides.ts
Default html index.html and index.tsx is used to boot and load react components.
I created stack.html file and accordingly i have created stack.tsx file as entry point to boot and load react components. I am unable to wire things up.
What configuration should be made to wire this up.
It is possible to do this, but you will need to eject from CRA. After that:
Add entry to the other html file in paths.js.
Update entry inside webpack.config.js and add the second html file entry (to be similar to the original entry).
Change the output file name inside webpack.config.js. Change static/j/bundle.js to static/js/[name].bundle.js.
Upadte webpack plugins to generate second file with injected JS scripts (also inside webpack.config.js).
Update the ManifestPlugin configuration to include the new entry point (also inside webpack.config.js).
Finally, there are two different steps for development and production.
For DEV, rewrite paths using the following in webpackDevServer.config.js (if you want to redirect all /admin to admin.html file):
verbose: true,
rewrites: [
{ from: /^/admin/, to: '/admin.html' },
],
For Production, this step is different for each provider. For Heroku, it is very easy, just create a static.json file with the following content:
{
"root": "build/",
"routes": {
"/admin**": "admin.html",
"/**": "index.html"
}
}
For full details and file diffs, see this post.
AFAIK, there are no good ways of doing this.
One way is to just use react-scripts and build multiple apps by copying and replacing index.html and index.js for each build. Something like
https://gist.github.com/jkarttunen/741fd48eb441137404a168883238ddc1
Also for CRA v3, there is an open PR for fixing this: https://github.com/facebook/create-react-app/pull/8249
I'm building a React / TypeScript app via Create React App and am looking to include environment specific configuration in a type safe way. Caveat, I really would rather not eject the app.
Ideally, I would like to have a set of files local.ts, dev.ts, prod.ts, etc. Each file would export an object of the same type, something like the following:
interface EnvConfig {
key: string
// ...
}
export const config: EnvConfig = {
key: 'value',
// ...
}
Then, in my app I'd like to import the appropriate config based on the environment. Something along the lines of:
// This is bundling BOTH prod and local configs and running logic client side!
if (process.env.NODE_ENV === 'production') {
return require('./prod')
} else {
return require('./local')
}
I have tried this and it sort of works, but if you look at the bundle react-scripts is including ALL of the config objects and running the logic on the client to determine which one to serve up. I don't want to ship ALL of my configs, only the appropriate config for the build.
Is there a way to do this without ejecting the app?
I have a project folder which contains both Web and Mobile application developed on React and React-native, There is a dependency for web which adds SymLink in the postinstall script, The problem I am facing is React-native Packager server also picks up that symlink and App doesnt work correctly.
At first I followed this- how to make react native packager ignore certain directories but getBlacklistRE silently ignores whatever Regex I am passing.
EDIT
This is the actual issue I am facing and I have tried implemented all the solutions mentioned there but no success yet. - https://github.com/facebook/react-native/issues/19763
EDIT2
Now seems to me blacklisting not working and it could also happen due to clashes between the babel version I am using in web and that of React Native below is my package.json
You mention trying blacklist with no luck. I don't have a web and react native project side by side but I do have a web project nested inside my react native project so this may be of some help. The blacklist does work for me and this is how it is implemented.
In rn-cli.config.js
const blacklist = require('metro/src/blacklist');
module.exports = {
getTransformModulePath() {
return require.resolve('./customTransformer'); // More on this below
},
getBlacklistRE() {
return blacklist([
/apps\/.*/,
]);
},
};
I have a directory called apps/ in the root of my project. Inside apps/ I have the equivalent of React Native's UI Explorer (a nested React Native app) and web documentation (React web app). By blacklisting this directory the react native packager at the root of my project won't load those node modules, otherwise there is unwanted collision.
The customTransformer may not be of direct help here but I include it incase it lends a hand to your situation. I use it to replace local mock data files with an empty object so that my final builds have mocked data stripped. There may be a way this helps your project out if you're not aware of it.
// Note transformer was renamed to reactNativeTransformer effective in RN 0.56.x
const upstreamTransformer = require('metro/src/reactNativeTransformer');
module.exports.transform = function (input) {
const { filename, options, src } = input;
let newSrc = src;
if (filename.indexOf('mocks') > -1 && !options.dev) {
newSrc = 'module.exports = {}';
}
return upstreamTransformer.transform({ src: newSrc, filename, options });
};