I'm usimg electron-react biolerplate.electron's main.js file placed in public folder.I want to add another electron file to common constants,functions.when I try to use that file it throws above error.
I want to keep main.js short .that's why I'm using another file
/public/renderer/command-executor.js
export const executeCommandWithOutput=(command)=>{
const { exec } = require('child_process');
console.log(command);
return new Promise((resolve, reject) => {
console.log('inside promise');
exec(command, (err, stdout, stderr) => {
console.log('inside execsync');
if (err) {
console.log(err);
resolve(err);
} else if (stderr) {
console.log(stderr)
resolve(stderr);
} else {
resolve(stdout);
}
});
});
}
public/main.js
const commandExecutor=require('./renderer/command-executor');
electron.ipcMain.on('launch-App',async(event,args)=>{
commandExecutor.executeCommandWithOutput(`powershell -Command "& {Start-Process -Verb runas '${playLink}'}"`);
});
The issue is that you're trying to mix the ES5 require statement with the ES6 syntax for export. The two are incompatible. You either have to use one or the other.
Assuming your ES6 implementation with babel works fine, you should use the import statement like this:
// exporting like you are at the moment (called a named export):
export const executeCommandWithOutput = (command) =>{
...
}
// importing like so:
import { executeCommandWithOutput } from './renderer/command-executor';
But if you're using require in public/main.js, your export statement should look something like this:
exports.executeCommandWithOutput = executeCommandWithOutput
and your require will remain the same.
Here's an article to help you get a better understanding of what's happening, how the export functionality works in ES5 and what you can achieve with it: https://www.sitepoint.com/understanding-module-exports-exports-node-js/
Likewise with the ES6 syntax:
https://alligator.io/js/modules-es6/
Related
Consider the following code in a "helper" module, which should not contains hooks.
//helpers/helpers.ts
import { useState } from 'react';
export function testLower() {
const [a, setAt] = useState('');
}
export function TestLower() {
const [a, setAt] = useState('');
}
The Eslint Plugin is able to detect, that the code in the lower-case function (testLower) contains a hook and throws a linting error.
But in the TestLower upper-case function - there is no error. This is because it "could" be a component identified by the UpperCase name, I would assume. In this case the hooks plugin does not have a chance of detecting the violation.
Since this slipped our code-review before - I would like to know:
Is there a way to disallow hooks with Eslint in a certain directory or module file in a code base?
I tend to favor good documentation, communication and team consensus on these topics over scripted handcuffs. If I absolutely need to reach this point then I'd try using a custom script that would run along eslint on your build process and/or pipelines.
/*
* noReactHooksAllowed.js
*
* usage
* node ./noReactHooksAllowed.js path/to/dir
*/
const fs = require('fs');
const dir = process.argv[2];
fs.readdirSync(dir).forEach(filename => {
const file = dir + '/' + filename;
console.log("Checking:", file);
try {
const sourceCode = fs.readFileSync(file, 'utf8');
if (/(useState|useEffect)/.test(sourceCode)) {
console.error("You shall not pass!");
console.error("Please remove react hooks from", file);
process.exit(1);
}
} catch (err) {
console.error(err);
}
});
console.log("No naughty hooks used here, carry on :)");
process.exit(0);
You can call it from your npm scripts and if it fails, the process.exit(1) signal should stop the whole build. This is a simple example but you can change the script to include more custom checks, have better performance with async calls, check just one file, etc.
I am new in Jest. I tried to write test for basic function which is
export const queryValidate = (query) => {
const str = query.replace(/\s+/g, "");
const conditionsArray = [
str === "",
str === "{",
str === "}",
str === "{}",
];
if (conditionsArray.includes(true)) {
return true;
} else {
return false;
}
};
In my Jest test file like that
import { queryValidate } from "./components/QueryValidate";
console.log(queryValidate("{"));
I am getting this error message :
import { queryValidate } from "./components/QueryValidate";
SyntaxError: Cannot use import statement outside a module
I cannot understand it is about Jest error or React module error. I try a write dummy test like :test("Fake test", () => {
expect(true).toBeTruthy();
});
Its work .
Can someone help me?
I don't have enough reputation to add a comment, therefore I'm adding an answer. I faced the same issues a while back.
As Estus has mentioned in the comment, you need to change the Jest config.
You can also have a look at babel-jest and then set a babel config file/ .babelrc, along with the preset env.
I'm using a stub file to mock images in my application, which works 99% of the time for me. However, I have a component that will render different images based on input, so I want to be able to check in my unit tests that the input creates the correct output.
Basically what I'm looking to do is if the user inputs "Lion", my component will display a picture of a lion, "Tiger a tiger, etc. Using moduleNameMapper, it's always test-file-stub and I want to be able to jest.mock('../lion.svg', ()=> 'lion.svg') for specific tests.
Thanks to Jest's transform config setting you may do that.
package.json
"jest": {
"transform": {
"\\.svg$": "<rootDir>/fileTransformer.js"
}
...
}
IMPORTANT
You need to explicitly provide transform to other extensions (especially *.js and *.jsx) otherwise you will get errors. So it should be something like:
"transform": {
"^.+\\.js$": "babel-jest",
"\\.svg$": "<rootDir>/fileTransformer.js"
...
}
As for fileTransformer.js it just emulates exporting file's path(you may add any transformation to strip the path or extension or whatever):
const path = require('path');
module.exports = {
process(src, filename) {
return `module.exports = ${JSON.stringify(path.basename(filename))};`;
}
};
It means
import svgIcon from './moon.svg';
will work just like
const svgIcon = 'moon.svg'
So for component containing
...
<img src={svgIcon} />
you may write assertion like
expect(imgElementYouMayFind.props.src)
.toEqual('moon.svg')
Just a small addition to what #skyboyer suggest:
module.exports = {
process(src, filename) {
return `module.exports = ${JSON.stringify(path.basename(filename))}`;
}
};
instead you need have it like that:
module.exports = {
process(filename) {
return `module.exports = ${JSON.stringify(path.basename(filename))};`;
}
};
pay attention to ; after closing curly bracket.
I have many console.log in my code.
As we know those logs slow down app a lot, so at the end of development I need to delete all of them, but of course I don't remember all the places where I have it. How can I use some wrapper for console.log which I can use, so that I could turn on or turn off all the console logs in one place? If my approach is not very good, advise me some libraries, tools, ways of doing what I need...
You can do this in the following two ways:
if(!__DEV__) {
console = {};
console.log = () => {};
console.error = () => {};
}
a better approach would be to use babel plugin transform-remove-console by
creating .babelrc file, and setting up babel transpiler.
example setup:
{
"presets": ["react-native"],
"env": {
"production": {
"plugins": ["transform-remove-console"]
}
}
}
source: https://facebook.github.io/react-native/docs/performance.html#using-consolelog-statements
Use this: https://github.com/babel/minify/tree/master/packages/babel-plugin-transform-remove-console
or you can creat a function in utils like this:
export const showLog = (tag, log) => {
console.log(tag + ' : ' + log);
};
and use showLog anywhere in your project:
import { showLog } from '../utils/utils';
showLog('VideoPlayer', response)
At the end, I've chosen the method described here - https://levelup.gitconnected.com/step-up-your-console-messaging-game-in-your-react-app-42eee17659ec
I like it best of all.
Upd: As Chmac mentioned (thanks), the link is dead. Archive link here
I want a Config File (JSON) in root folder after build to config my app.
like Translation and API Urls and ...
Can I do this with create react app?
Create config.js or json file outside src directory and include it in index.html like
<script src="%PUBLIC_URL%/config.js" type="text/javascript"></script>
configure parameters in config.js
config.js
var BASE_URL = "http://YOUR-URL";
you can get paramenters like
const BASE_URL = window.BASE_URL;
You can store you JSON file in the public/ folder and it'll automatically provide this file when you host your Create React App.
Something like: /public/my-configuration-file.json
then when you restart your application:
localhost:3000/my-configuration-file.json
will provide you this json file.
You could create a custom hook that reads a "public" config file using fetch.
// This path is relative to root, e.g. http://localhost/config.json
const configFile = './config.json'
export function useConfig() {
const [config, setConfig] = useState(initialConfig);
useEffect(() => {
(async function fetchConfig() {
try {
const response = await (await fetch(configFile)).json();
setConfig(response);
} catch (e) {
console.log(e);
}
}());
}, []);
return config;
}
Then use it anywhere in you app
function App() {
const config = useConfig();
return (
<div>{config.foo}</div>
);
}
You'll always have an up to date non-cached version of it's data.
updating this topic with a brand new package that is available now that brings the joys of .Net Configuration to the JavaScript world: wj-config.
This package is pretty much an exact answer to what you need. Read this blog post for more information.
It is incredible to me how during over 6 years nobody filled in this gap in React (and JavaScript in general). Anyway, give wj-config a try. I think it will be a positive experience.