DOMcollection.js failed to compile in React Environment - javascript

I am new to react and there is a problem while solving the error.
May I ask please what is missing in my project environment please?
The following message appears:
**Failed to compile**
./node_modules/#testing-library/dom/node_modules/pretty-format/build/plugins/DOMCollection.js
Module parse failed: Unexpected token (53:15)
You may need an appropriate loader to handle this file type.
| return props;
| }, {})
| : {...collection},
| config,
| indentation,
webpack.config.dev.js file:
This file is being generated after the npm run eject command.
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');

I don't know if it is a good long term solution but I was having this issue and changed react-scripts to version 4.0.1 with npm install react-scripts#4.0.1 and my dev environment is up again.

Okay, so the first step is having the DOMCollection.js file opened and then resolving the {...collection} to collection,
Save the file and reload the page.DOMCollection
so from : {...collection}
config,
indentation,
depth,
refs,
printer
to :
collection,
config,
indentation,
depth,
refs,
printer

Related

Why can't you read package.json in a builded electron app?

Hello Stackoverflow users!
I am trying to place all of the configuration for the electron app in the package.json file.
Here is my code snippet:
index.js
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
function readConf() {
const data = fs.readFileSync('./package.json', 'utf8');
return data;
}
ipcMain.on('synchronous-message', (event, arg) => {
event.returnValue = readConfig();
})
index.html
<script type="text/javascript">
const { ipcRenderer } = require('electron')
config = JSON.parse(ipcRenderer.sendSync('synchronous-message', ''))
</script>
<h1>Version of <script>document.write(config.name)</script> is <script>document.write(config.version);</script></h1>
The code is working when you run the app via npm start, but when you make it into an exe with electron-forge and squirrel (npm make) and try to run it after installing it throws an error that the package.json file can't be found.
So what do you need to specify as the path to the file to read it in the built app?
I am using electron forge.
I found a way to fix the issue!
Instead of
const data = fs.readFileSync('./package.json', 'utf8');
You'll need to write
const data = fs.readFileSync(__dirname + '/../package.json', 'utf8');

How would I get webpack or an other JS bundler to bundle files remotely hosted?

I have a distributed system and all JS files are exposed through HTTP. So a normal module would look like this:
http://example.com/path/to/main.js
import * as core from 'http://local.example.com/path/to/core.js';
import * as redux from 'http://cdn.example.com/redux.js#version';
// code
export default {
...
}
So each import will be using either a local resource to the system or possibly remotely available resources using CDN.
Thought when I run webpack, I get this error:
trying to parse a local generated file with such content:
import * as main from 'http://example.com/path/to/main.js';
ERROR in ./src/index.js Module not found: Error: Can't resolve
'http://example.com/path/to/main.js' in '/home/.../index.js'
Is it possible to tell webpack to fetch the urls and include them inside the bundle... While packaging cdn urls isn't a big deal for now, I'd be happy if I could simply ignore the ones with a certain url.
Thought being able to bundle remote all the http:// located files would be a good start.
Also, any remote resource linking to other resources should recursively load remotely linked resources too.
Here's my current webpack config (thought nothing much to see here):
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
]
},
};
Edit: after reading a bit, I started writing a resolver but now I'm stuck again:
const path = require('path');
const fetch = require('node-fetch');
const url = require('url')
const fs = require('promise-fs');
const sha1 = require('sha1')
class CustomResolver {
async download_save(request, resolveContext) {
console.log(request, resolveContext)
var target = url.parse(request.request)
var response = await fetch(request.request)
var content = await response.text()
try {
await fs.stat('_remote')
} catch(exc) {
await fs.mkdir('_remote')
}
var filename = `${sha1(request.request)}.js`
var file_path = `_remote/${filename}`
await fs.writeFile(file_path, content)
var abs_path = path.resolve(file_path)
var url_path = `${target.protocol}://${target.hostname}/`
var obj = {
path: abs_path,
request: request.request,
query: '',
}
console.log(`${request.request} saved to ${abs_path}`)
return obj
}
apply(resolver) {
var self = this
const target = resolver.ensureHook("resolved")
resolver.getHook("module")
.tapAsync("FetchResolverPlugin", (request, resolveContext, callback) => {
self.download_save(request, resolveContext)
.then((obj) => resolver.doResolve(target, obj, resolveContext, callback))
.catch((err) => {
console.log(err)
callback()
})
})
}
}
It does currently fetch urls starting with https:// but seems to be struggling to resolve urls relative to an http resource. For example
ERROR in _remote/88f978ae6c4a58e98a0a39996416d923ef9ca531.js
Module not found: Error: Can't resolve '/-/#pika/polyfill#v0.0.3/dist=es2017/polyfill.js' in '_remote/'
# _remote/88f978ae6c4a58e98a0a39996416d923ef9ca531.js 25:0-58
# _remote/f80b922b2dd42bdfaaba4e9f4fc3c84b9cc04fca.js
# ./src/index.js
It doesn't look like it tries to resolve relative path to already resolved files. Is there a way to tell the resolver to try to resolve everything?
Main point is: if you have CDN files - you don't need a bundler.
They already minified and ready to use. Just import files in root of your project and call libraries globally.

When I try to run npm test with mocha, in my cmd it says "Error: Cannot find module 'path' " does anyone know how to solve this?

When I try to run npm test with mocha, in my cmd it says Error: Cannot find module 'path'
I am a total beginner in this area and just trying to write some really simple code. I am using Mocha as my test frame, it worked totally fine yesterday and today it's down.
I tried npm install -D #types/path, it did not work out.
Here is my code in Inbox.test.js file:
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');//capitalize when working with a constructor function
const web3 = new Web3(ganache.provider());//local instance
const {interface, bytecode} = require('../compile');
let accounts;
let inbox;
beforeEach(async ()=>{
//Get a list of all accounts
web3.eth.getAccounts()
accounts = await web3.eth.getAccounts();
//Use one of the accounts to deploy
//the contrct
inbox = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data: bytecode, arguments:['Hi there!']})
.send({from: accounts[0], gas:'1000000'});//account[0] is the one
//who is really deploying the contract
});
describe('Inbox', () => {
it('deploys a contract', ()=>{
console.log(inbox);
});
});
Here is code in my compile.js file:
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const inboxPath = path.resolve(__dirname, 'contract', 'Inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8');
module.exports = solc.compile(source,1).contracts[':Inbox'];
The test frame Mocha should run through my code and print out the smart contract I created, instead it shows a error that says I am missing a module 'path'.
Here is the error I am getting:
Error: Cannot find module 'path '
Require stack:
- C:\Users\Alex Zhu\Desktop\Inbox\compile.js
- C:\Users\Alex Zhu\Desktop\Inbox\test\Inbox.test.js
- C:\Users\Alex Zhu\Desktop\Inbox\node_modules\mocha\lib\mocha.js
- C:\Users\Alex Zhu\Desktop\Inbox\node_modules\mocha\lib\cli\one-and-dones.js
- C:\Users\Alex Zhu\Desktop\Inbox\node_modules\mocha\lib\cli\options.js
- C:\Users\Alex Zhu\Desktop\Inbox\node_modules\mocha\lib\cli\cli.js
- C:\Users\Alex Zhu\Desktop\Inbox\node_modules\mocha\lib\cli\index.js
- C:\Users\Alex Zhu\Desktop\Inbox\node_modules\mocha\bin\_mocha

Workbox in Create React App without eject

I'm trying to configure Workbox in CRA without eject. Anyone succeeded?
After hours trialing and error I succeeded to have workbox in CRA. Here's how I did:
First,yarn add -D workbox-build
Next, create a file called build-sw.js in the root folder with:
const fs = require('fs-extra');
const pathmodule = require('path');
const workbox = require('workbox-build');
function build() {
const cwd = process.cwd();
const pkgPath = `${cwd}/node_modules/workbox-sw/package.json`;
const pkg = require(pkgPath);
const readPath = `${cwd}/node_modules/workbox-sw/${pkg.main}`;
let data = fs.readFileSync(readPath, 'utf8');
let path = `${cwd}/build/workbox-sw.js`;
console.log(`Writing ${path}.`);
fs.writeFileSync(path, data, 'utf8');
data = fs.readFileSync(`${readPath}.map`, 'utf8');
path = `${cwd}/build/${pathmodule.basename(pkg.main)}.map`;
console.log(`Writing ${path}.`);
fs.writeFileSync(path, data, 'utf8');
workbox
.injectManifest({
globDirectory: 'build',
globPatterns: ['**/*.{html,js,css,png,jpg,json}'],
globIgnores: ['sw-default.js', 'service-worker.js', 'workbox-sw.js'],
swSrc: './src/sw-template.js',
swDest: 'build/sw-default.js'
})
.then(_ => {
console.log('Service worker generated.');
});
}
try {
build();
} catch (e) {
console.log(e);
}
After that, create a file in src/sw-template.jswith:
(Have in mind that in this file is where you have to put your own cache strategy. See Docs for more info)
workbox.setConfig({
debug: true
});
workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);
workbox.precaching.precacheAndRoute([]);
workbox.skipWaiting();
workbox.clientsClaim();
workbox.routing.registerRoute('/', workbox.strategies.networkFirst());
Finally, in src/registerServiceWorker.js change:
- const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
+ const swUrl = `${process.env.PUBLIC_URL}/sw-default.js`;
And in package.json change:
- "build": "react-scripts build && sw-precache --config=sw-precache-config.js'",
+ "build": "react-scripts build && yarn sw",
+ "sw": "node build-sw.js"
Hope it helps!
With the merge of this PR, Create React App 2 now support supports Workbox out of the box, since it now uses workbox-webpack-plugins internally.
Take a look at the official docs to learn more: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

Gulp 4.0 signal async completion error despite returning stream

I have the following gulp task that returns a stream. It works fine in gulp 3.9.1, but converting to gulp 4.0, I get:
Did you forget to signal async completion?
const gulp = require('gulp');
const gulpif = require('gulp-if');
const plumber = require('gulp-plumber');
const rename = require('gulp-rename');
const buffer = require('vinyl-buffer');
const es = require('event-stream');
const browserify = require('browserify');
const browserifyInc = require('browserify-incremental');
const babelify = require('babelify');
const browserSync = require('browser-sync').create();
// Incrementally building the js
gulp.task('build-js-inc', () =>
es.merge.apply(null, paths.entry.scripts.map(script => {
const b = browserify(Object.assign({}, browserifyInc.args,
{
entries: script,
extensions: ['.jsx'],
debug: true
}
));
browserifyInc(b, { cacheFile: './browserify-cache.json' });
return b.transform(babelify)
.bundle()
.on('error', handleErrors)
.pipe(source(`./${script.split('/')[script.split('/').length - 1]}`))
.pipe(buffer())
.pipe(plumber())
.pipe(rename(path => {
path.extname = '.bundle.js';
}))
.pipe(gulp.dest('public/js'))
.pipe(gulpif('*sw.bundle.js', gulp.dest('public')))
.pipe(browserSync.reload({ stream: true }));
}))
);
I've tried adding done() to my upstream tasks, but it still errors because I'm thinking it originates here and propogates through my subsequent tasks that rely on this one finishing.
The problem ended up being the module event-stream. Apparently it is no longer being maintained.
#phated:
Support for event-stream is deprecated. Everything is supposed to move to through2, et al. Maybe just fully deprecate this module?
I switched to merge-stream and now my gulpfile works fine.

Categories

Resources