Unfamiliar with javascript/node.js, and I'm unable to get my script to run:
import { IDS, MangoGroup, MangoClient } from '#blockworks-foundation/mango-client';
import { Account, Connection, PublicKey } from '#solana/web3.js';
import { Market } from '#project-serum/serum';
import { readFileSync } from 'fs';
setInterval(function () {
console.log("timer that keeps nodejs processing running");
}, 1000 * 60 * 60);
As you can see, this script is essentially blank. The imports alone are causing it to fail. If I remove the imports, then node.js stays running.
What's the problem?
EDIT: Here is the output: gist
If you are trying to run the script using nodejs, add "type": "module" in the package.json file. I hope this will solve your issue.
Related
I got this basic Javascript code which is compiled by webpack. I am using Hot Module Replacement for Styles and Javascript.
When I listen to https://localhost:3000/mypage everything works perfectly.
However I would like the app() to run if the HMR can not connect:
GET http://localhost/__bud/hmr 404 (Not Found)
I am aware, that in this case my updates will not be applied.
This does currently work, however I have the feeling that it is not the correct way to do this.
My setup is:
WSL2 - Ubuntu
Wordpress 6.0
bud.js
Webpack
/**
* Import a file with the correct ES6 Module way:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
*/
import Cookie from './modules/Cookie.mjs';
import LazyLoadImages from './modules/LazyLoadImages.mjs';
/**
* app.main
*/
const main = async (err) => {
if (err) {
// handle HMR errors
console.error(err);
}
// application code
app();
/**
* Initialize
*
* #see https://webpack.js.org/api/hot-module-replacement
*/
import.meta.webpackHot?.accept(main);
};
/**
* Add custom code inside this function
*/
const app = () => {
document.addEventListener("DOMContentLoaded", function (event) {
// Add your imported code here, for example: new defaultExport();
new Cookie(true);
new LazyLoadImages();
});
}
/**
* Run the application even if HMR is not enabled/used
*/
app();
I'm building on Next.js app and when I install / import Plaiceholder (for generating placeholder images), I get the following error: Module not found: Can't resolve 'child_process'
Node v14.18.0
Next.js v11.1.2
Plaiceholder v2.2.0
Sharp v0.29.2
I understand this error message to mean that webpack5 is trying to bundle node packages that aren't available to the client. But I'm not clear why it is doing this. I haven't customized any of the webpack configs, and I can't find any mention of this issue in the Plaiceholder docs. How do I fix it?
NOTE: I want the base64 data URL to get created during the build, so that it available as soon as the page loads (not fetched asynchronously at run time).
Here's my next.config.js
module.exports = {
reactStrictMode: true,
};
My package.json only has scripts, dependencies, and devDependencies (nothing to change module resolution)
In case it's relevant, here's a simplified example using Plaiceholder:
import Image from "next/image";
import { getPlaiceholder } from "plaiceholder";
import React, { useState } from "react";
...
const { base64 } = await getPlaiceholder(imgUrl);
...
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
It seems like plaiceholder is not suitable for client-side rendering. I believe that package is for the Node.js environment. That's why you get this error when you try to render your component on the client side.
To solve this problem, you need to move import { getPlaiceholder } from 'plaiceholder' to the NextJS API section. Then you can call that API with your URL data in the body. Then get the base64.
/api/getBase64.js
import { getPlaiceholder } from "plaiceholder";
export default async (req, res) => {
const { body } = req;
const { url } = body;
const { base64 } = getPlaiceholder(url);
res.status(200).send(base64);
};
/component.js
import Image from "next/image";
import React, { useState, useEffect } from "react";
const [base64, setBase64] = useState()
useEffect(() => {
(async () => {
const _base64 = await fetch.post('/api/getBase64', {url: imgUrl}); // wrote for demonstration
setBase64(_base64);
})()
})
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
I know blurDataURL will be undefined until you fetch the data but this is the way how you can use plaiceholder library to manage your images. It should be imported only for the NodeJS environment. If you do not like this approach, you can try to find another library that also works for the browser environment (client)
UPDATED according to the comment:
If you want to generate this base64 at build time, you can use getStaticProps in the pages that use this Image component. NextJS is smart enough to understand which libraries are used in the client-side or server-side. So you can do this:
import { getPlaiceholder } from "plaiceholder"; // place it at the root of file. This will not be bundled inside of client-side code
export async function getStaticProps(context) {
const { base64 } = await getPlaiceholder(imgUrl);
return {
props: { base64 }, // will be passed to the page component as props
}
}
This way, by using getStaticProps, the page will be created at build time. You can get the base64 prop inside of the page that uses the image component and pass that prop to blurDataURL. Also, you can use this approach with getServerSideProps too.
This is from NextJS website:
Note: You can import modules in top-level scope for use in
getServerSideProps. Imports used in getServerSideProps will not be
bundled for the client-side.
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
It's necessary to Install plugin for Next Js dependency and configure next config based on Plaiceholder Docs for using getPlaiceholder() function in getStaticProps like the answer by #oakar.
npm i #plaiceholder/next
const { withPlaiceholder } = require("#plaiceholder/next");
module.exports = withPlaiceholder({
// your Next.js config
});
I have created a javascript library with webpack, that outputs a systemjs module. This module has a dependency on react, which I specified as an external.
The resulting javascript file starts like this:
System.register(["react"], function(__WEBPACK_DYNAMIC_EXPORT__) {
var __WEBPACK_EXTERNAL_MODULE_react__;
return { ....
Additionally I have an app, that uses SystemJS during runtime to load that module. In order to provide the react dependency, I have defined an importmap:
{
"imports": {
"react": "https://unpkg.com/react#16.11.0/umd/react.production.min.js"
}
}
And the part, where I import the module, looks like this:
const modulePromise = System.import(MODULE_URL);
modulePromise.then(module => {
console.log('module loaded successfully!');
});
The problem now is, that the console.log is never called, because I get a TypeError, that says, that "Component is not a property of undefined", which tells me, that somehow react has not correctly been passed to my module.
To be precise, in the browser network tab I see, that my module and the react import is indeed loaded, but somehow it is not correctly processed.
Has anyone an idea, what i might be doing wrong?
OK, so eventually I solved this myself, although a bit different.
First, I did not use the unpkg link anymore, but I actually include React as a library in my main app.
And I changed my importmap to:
<script type="systemjs-importmap">
{
"imports": {
"react": "app:react",
"react-dom": "app:react-dom"
}
}
</script>
Also in the main app I use System.set(...) from SystemJs to tell SystemJS where to find the 'app:react' and 'app:react-dom' dependencies:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import 'systemjs/dist/system.min';
...
System.set('app:react', { default: React, __useDefault: true });
System.set('app:react-dom', { default: ReactDOM, __useDefault: true });
And now, if I load my module with that external react dependency through SystemJS, it works.
I'm working with quite large data in MongoDB and using it in my Meteor application. However, the size of the data is causing the webpage to load incredibly slowly.
The collection is around 17MB in size and contains 84,000 documents.
Using the Publish/Subscribe method I have the following code:
Imports -> Both -> MyCollection.js:
import { Mongo } from 'meteor/mongo';
export const statistics = new Mongo.Collection('statistics');
Server -> Main.js:
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';
import { statistics } from '/imports/both/MyCollection';
Meteor.publish('statistics', function publishSomeData() {
return statistics.find();
});
Client -> Main.js:
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { statistics } from '/imports/both/MyCollection';
import './main.html';
Template.application.onCreated(function applicationOnCreated() {
this.subscribe('statistics');
});
Template.application.onRendered(function applicationOnRendered() {
this.autorun(() => {
if (this.subscriptionsReady()) {
const statisticsData = statistics.findOne();
console.log(statisticsData);
}
});
});
So like I say this method works and the console logs the data. However, using an internet connection of around 60mbps it takes around 2 minutes to load the page and finally console log the data and sometimes I just get the 'Google is not responding' alert and I'm forced to force quit.
What is a more efficient means of loading the data into the application in order to avoid this terribly slow loading time? Any help would be greatly appreciated.
Many thanks,
G
Limit the amount of data you publish to the client.
Either only publish some fields of the statistics collection or 'lazy load' documents - pass a number of docs argument to the publication and use the limit option of find to only send that many docs to the client.
Alternatively, compile the data as needed on the server and only send the compiled data to the client.
Much more specific examples cannot be given without knowing the collection's nature.
I'm having a great deal of trouble using Enzyme and Mocha to test my React project. I have a test like this:
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import { ChipInput} from '../client/components/Chips';
describe('<ChipInput />', _ => {
it('rocks', done => {
done();
});
});
And when ChipInput gets imported, that file imports something with an absolute path, e.g. /lib/collections/tags, and then Mocha errors out because it apparently only does relative paths. How do I get this working?
EDIT:
The actual error:
Error: Cannot find module '/lib/collections/tags'
This happens because /tests/ChipInput-test.js imports the ChipInput component from /client/components/Chips/index.js, which has the following lines:
import React from 'react';
import {
MapsLocalOffer as TagIcon,
ImageRemoveRedEye as InsightIcon,
EditorInsertChart as TestIcon,
SocialPerson as UserIcon,
} from 'material-ui/svg-icons';
import { Tag } from '/lib/collections/tags'; // error thrown here
import { Insight } from '/lib/collections/insights';
// import { Test } from '/lib/collections/tests';
import Chip from './Chip';
import ChipDisplay from './ChipDisplay';
import ChipInput from './ChipInput';
import * as chipTypes from './chip-types';
To anyone hitting here from google, while ffxsam's answer will work, there are many ways to accomplish this. Node's require allows for a base to be set either via environment variable or programmatically, allowing for simple absolute paths that don't require the leading slash (require("my/module"); vs require("/my/module");).
I use gulp as a taskrunner, so my preferred technique is to use app-module-path to do the following at the top of my gulpfile (this will work anywhere, so long as you haven't encountered any absolute requires yet):
require('babel-core/register'); //for mocha to use es6
require('app-module-path').addPath(__dirname + '/src'); //set root path
//I also use webpack to pull in other extensions, so I
//want mocha to noop out on them
require.extensions['.css'] = _.noop;
require.extensions['.scss'] = _.noop;
require.extensions['.png'] = _.noop;
require.extensions['.jpg'] = _.noop;
require.extensions['.jpeg'] = _.noop;
require.extensions['.gif'] = _.noop;
For a more complete rundown, check out this gist by github user branneman: https://gist.github.com/branneman/8048520
This has been awhile, but I want to share my solution here, just in case, all solutions above don't work in your specific situation. I was looking for a solution to fix our unit test, which failed "Error: Cannot find module 'components/shared/xyz', our 'components' folder is under 'client/src' folder, so I came up with the following solution which works for us.
npm install babel-plugin-module-resolver --save-dev
{
'plugins': [
'babel-plugin-module-resolver',
{ 'root': ['client/src'] }
]
}
Here's the solution, nice and simple!
https://github.com/mantrajs/babel-root-slash-import
Basically, install said package:
npm install babel-root-slash-import --save-dev
Add the plugin to .babelrc:
{
"plugins": [
"babel-root-slash-import"
]
}
And it's good to go.