How to disable devtools sourcemaps for React/ElectronJS application - reactjs

thanks for taking the time to look at this. Here's the issue at hand:
I am building a desktop application using ElectronJS and React. But every time that I load the project, I get these annoying warnings about sourcemaps in the console:
I know that the manual solution is to go into the dev tool settings every time I run the project and uncheck these boxes:
However, is there a way to configure this so I don't have to do this each time I load the project? It's very cumbersome and annoying.
In case you need it, here are my package.json scripts (I use "app" to run it)
"scripts": {
"app": "concurrently \"cross-env BROWSER=none npm start\" \"wait-on http://localhost:3000 && electron .\" \"npm run watch-css\"",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"build-css": "node-sass ./src/css/sass_css/ -o ./src/css/vanilla_css/",
"watch-css": "nodemon -e scss -x \"npm run build-css\"",
"eject": "react-scripts eject"
},
Yes I used create-react-app. Added my webpack config:
#!/usr/bin/env node
/**
* #param {string} command process to run
* #param {string[]} args command line arguments
* #returns {Promise<void>} promise
*/
const runCommand = (command, args) => {
const cp = require("child_process");
return new Promise((resolve, reject) => {
const executedCommand = cp.spawn(command, args, {
stdio: "inherit",
shell: true
});
executedCommand.on("error", error => {
reject(error);
});
executedCommand.on("exit", code => {
if (code === 0) {
resolve();
} else {
reject();
}
});
});
};
/**
* #param {string} packageName name of the package
* #returns {boolean} is the package installed?
*/
const isInstalled = packageName => {
if (process.versions.pnp) {
return true;
}
const path = require("path");
const fs = require("graceful-fs");
let dir = __dirname;
do {
try {
if (
fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()
) {
return true;
}
} catch (_error) {
// Nothing
}
} while (dir !== (dir = path.dirname(dir)));
return false;
};
/**
* #param {CliOption} cli options
* #returns {void}
*/
const runCli = cli => {
const path = require("path");
const pkgPath = require.resolve(`${cli.package}/package.json`);
// eslint-disable-next-line node/no-missing-require
const pkg = require(pkgPath);
// eslint-disable-next-line node/no-missing-require
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
};
/**
* #typedef {Object} CliOption
* #property {string} name display name
* #property {string} package npm package name
* #property {string} binName name of the executable file
* #property {boolean} installed currently installed?
* #property {string} url homepage
*/
/** #type {CliOption} */
const cli = {
name: "webpack-cli",
package: "webpack-cli",
binName: "webpack-cli",
installed: isInstalled("webpack-cli"),
url: "https://github.com/webpack/webpack-cli"
};
if (!cli.installed) {
const path = require("path");
const fs = require("graceful-fs");
const readLine = require("readline");
const notify =
"CLI for webpack must be installed.\n" + ` ${cli.name} (${cli.url})\n`;
console.error(notify);
let packageManager;
if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
packageManager = "yarn";
} else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
packageManager = "pnpm";
} else {
packageManager = "npm";
}
const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
console.error(
`We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
" "
)} ${cli.package}".`
);
const question = `Do you want to install 'webpack-cli' (yes/no): `;
const questionInterface = readLine.createInterface({
input: process.stdin,
output: process.stderr
});
// In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
// executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
// function is responsible for clearing the exit code if the user wishes to install webpack-cli.
process.exitCode = 1;
questionInterface.question(question, answer => {
questionInterface.close();
const normalizedAnswer = answer.toLowerCase().startsWith("y");
if (!normalizedAnswer) {
console.error(
"You need to install 'webpack-cli' to use webpack via CLI.\n" +
"You can also install the CLI manually."
);
return;
}
process.exitCode = 0;
console.log(
`Installing '${
cli.package
}' (running '${packageManager} ${installOptions.join(" ")} ${
cli.package
}')...`
);
runCommand(packageManager, installOptions.concat(cli.package))
.then(() => {
runCli(cli);
})
.catch(error => {
console.error(error);
process.exitCode = 1;
});
});
} else {
runCli(cli);
}

You can use create a file .env and add
GENERATE_SOURCEMAP=false
This will remove any .map files from your build/static/js folder the next time you run build.

Related

React/Vite Build Error causing a Reducer to be wrongly exported

Hi I'm having a very weird error during build process of a React application with Vite.
When I run Vite as a dev server on local machine it works well, but during the build process there is an error on the resultant code.
The problem is actually with one reducer, which is not being exported as it should be, causing an error on the components that depends on that slice.
This is the generated source relating to the reducer causing issues:
var m = (0,
e.createSlice)({
name: "form",
initialState: {
list: {}
},
reducers: {
generateForm: function(q, j) {
var L = j.payload
, K = L.id
, U = L.fields
, W = L.values
, X = L.baseUrl
, ae = (0,
t.normalizeFields)(U);
q.list[K] = {
fields: ae,
values: W || null,
baseUrl: X || null
}
}
}
}
});
de.formSlice = m;
var E = m.actions,
h = E.generateForm;
de.generateForm = h;
var V = m.reducer;
return de.default = V,
de
While all other reducers work as intended, and build correctly, they look like this one for example:
var Wc = (0,
HE.createSlice)({
name: "datatable",
initialState: {
list: {}
},
reducers: {
clear: function(r, t) {
var n = t.payload.id;
delete r.list[n]
}
}
});
St.clear= Wc;
var Ml = Wc.actions
, GE = Ml.clear;
var sh = St.clear = GE
, XE = Wc.reducer
, ch = St.default = XE
, xt = {}
, Il = {};
Notice that the reducer that is failing is somehow returning both the entire slice object and the default export, while all other reducers simply assign the reducer to the default export.
The weird thing is that if I go with react-scripts all builds correctly, but I'd like to know why and If I'm missing a plugin or something.
My vite config looks like this:
export default defineConfig(({ mode }) => {
process.env = {
...process.env,
...process.env.development,
...loadEnv(mode, process.cwd())
};
return {
base: process.env.VITE_APP_BASENAME,
server: {
port: 3000
},
plugins: [
react({
babel: {
babelrc: true,
parserOpts: {
plugins: ["decorators-legacy"]
}
}
}),
EnvironmentPlugin("all", { prefix: "REACT_APP_" }),
istanbul({
include: ["src"],
exclude: ["node_modules", "test/", "cypress/"],
extension: [".js", ".jsx"]
})
],
build: {
rollupOptions: {
output: {
manualChunks: {
"react-venders": ["react", "react-dom"]
}
},
external: ["#vitjs/runtime"]
},
chunkSizeWarningLimit: 700
}
};
});
My .babelrc config is the following:
{
"presets": ["#babel/react"]
}
Also is pretty rare that in local serve mode (npm start) which runs Vite it does works well. It only fails during build process, and specifically on that Reducer (form).
Appreciate any help! Thanks

How to use custom style loader in Vite

We have a react project and using webpack for bundling but also we want to try vite too. Webpack bundle css files from style-loader.js too. In style-loader.js we have some rules which are related to components and components are added to node modules. My rule's aim is mainly importing css files from node_modules components. When we run our project with vite, Our custom scss files does not override css which came from components. Is there any solution for override or Is there any way to use a custom style loader in vite ?
Our custom style loader webpack-dev is;
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: './config/webpack/style-loader'
},
]}
Our style-loader.js file is;
const babylon = require('babylon');
const traverse = require('babel-traverse').default;
const fs = require('fs');
module.exports = function (source) {
var astResult = babylon.parse(source, {
sourceType: "module",
ranges: true,
plugins: [
"jsx",
"objectRestSpread",
"flow",
"typescript",
"decorators",
"doExpressions",
"classProperties",
"classPrivateProperties",
"classPrivateMethods",
"exportExtensions",
"asyncGenerators",
"functionBind",
"functionSent",
"dynamicImport",
"numericSeparator",
"optionalChaining",
"importMeta",
"bigInt",
"optionalCatchBinding"
]
});
let addedIndexCounter = 0;
let isViewDirty = false;
traverse(astResult, {
enter: function (path) {
let node = path.node;
if (node.type == 'ImportDeclaration' &&
node.source &&
node.source.type == 'StringLiteral' &&
node.source.value &&
node.source.value.indexOf('#packagename') >= 0 &&
node.source.value.indexOf('core') < 0 &&
node.source.value.indexOf('.css') < 0) {
if(fs.existsSync('./node_modules/' + node.source.value + '/styles.css')) {
let starting = node.end;
starting += addedIndexCounter;
let targettacCss = "; import '" + node.source.value + "/styles.css';"
addedIndexCounter += targettacCss.length;
source = source.substring(0, starting) + targettacCss + source.substring(starting);
isViewDirty = true;
}
}
}
});
/*if(isViewDirty){
let fileName = "view_" + (new Date()).toISOString().slice(0, 10)+"_" + Math.random().toString(35).substr(2,10);
fs.writeFileSync('./logs/views/' + fileName, source);
}*/
return source;
};
You can use plugins to achieve your feature, the following is my general idea.
// vite.config.js
import { defineConfig } from "vite";
import customerPlugin from "./plugin/customer-plugin";
export default defineConfig(() => {
return {
// ..
plugins: [customerPlugin()] // Put your plugin here
};
});
// ./plugin/customer-plugin.js
const customerPlugin = () => {
return {
name: "customer-transform",
transform(code, id) {
// id = "/some/path/xxx.js"
if (!id.endsWith(".js")) return; // Only transform js file.
let resultCode = "";
// Paste your transform logic here.
return resultCode;
}
};
};
export default customerPlugin;
reference: https://vitejs.dev/guide/api-plugin.html

How to create a Discord bot which simply plays local audio files into your channel?

I was wondering how to create such a Discord bot, playing music files stored in my PC (and not from any internet source like youtube...).
I read this solution, but some corrections have to be made for discord.js v12
So this is a simply code I made for discord v12. (Note that I'm a fresh beginner in javascript, so if any mistake is made, please tell me)
settings.json
{
"token" : "{YOUR TOKEN}",
"filesDir" : "./files/",
"commandPlay" : ["!playLocal", "!playlocal"],
"commandStop" : ["!stopLocal", "!stoplocal"],
"commandList" : ["!playLocal list", "!playlocal list"],
"warningPlayArgsSentence" : "Aucun argument renseigné, veuillez informer du titre du fichier à jouer. Exemple : !playLocal FoxMix",
"filesListSentence" : "Liste des fichiers .mp3 disponibles : ",
"warningFolderNotFoundSentence" : "Ce répertoire semble être impossible à scanner : "
}
index.js
const settings = require('./settings.json')
const Discord = require('discord.js')
const fs = require('fs');
var isReady = true;
const bot = new Discord.Client();
function startsWithInList(message, list) {
var found = false;
list.forEach(function (item) {
if( message.startsWith(item) ) {
found = true;
}
})
return found;
}
function foundsInList(message, list) {
var found = false;
list.forEach(function (item) {
if( message === item ) {
found = true;
}
})
return found;
}
bot.on( 'message', message => {
if( foundsInList(message.content, settings.commandList) ) {
fs.readdir( settings.filesDir, function (err, files) {
if(err) {
return message.channel.send(settings.warningFolderNotFoundSentence+settings.filesDir);
}
let listTxt = "";
files.forEach(function (file) {
if( file.endsWith('.mp3') || file.endsWith('.MP3') ) {
listTxt += `\`${file.split('.')[0]}\` `;
}
})
message.channel.send(settings.filesListSentence);
message.channel.send(listTxt);
})
return;
}
if( isReady && startsWithInList(message.content, settings.commandPlay) ) {
isReady = false;
const args = message.content.slice(10).trim().split(' ');
if( args.length != 1 || !args[0] || args[0] === "" ) {
return message.channel.send(settings.warningPlayArgsSentence);
}
var voiceChannel = message.member.voice.channel;
voiceChannel.join().then( connection => {
const dispatcher = connection.play(settings.filesDir+args[0]+'.mp3')
dispatcher.on('finish', () => {
voiceChannel.leave();
isReady = true;
})
});
}
if ( startsWithInList(message.content, settings.commandStop) ) {
message.member.voice.channel.leave();
isReady = true;
}
})
bot.login(settings.token);
For those who are lost and never made a bot :
Look on the net for "How to create a discord bot"
Download ffmpeg binaries (which will be placed in working folder) + Install node.js from the net
run in Windows PowerShell
npm init
npm install discord.js
npm install -g windows-build-tools
npm install node-opus
And finaly, create a folder called "files" in working directory and put your .mp3 into.
Run with
node .\index.js
And test the "!playLocal musicFile" discord comment

vscode findFiles returns nothing but npm glob returns correct results

I'm writing and vscode extension in which I need a list of the test files inside workspace.
To find the test files I'm using the default testMatch from the jest.config.js which is:
[
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)'
]
My problem is that vscode.workspace.findFiles returns empty array and I cannot set it up to get correct results, but using Glob package the output is correct.
protected async findTestFiles(
matchTestsGlobPatterns: string[]
): Promise<vscode.Uri[]> {
const testFilesUris: vscode.Uri[] = [];
const glob_testFilesUris: vscode.Uri[] = [];
const { name: workspaceName, workspaceFolders } = vscode.workspace;
if (workspaceName === undefined || workspaceFolders === undefined) {
throw new Error(`No active workspace${!workspaceFolders ? ' folders' : ''}.`);
}
for (let folderIdx = 0; folderIdx < workspaceFolders.length; folderIdx++) {
const folder = workspaceFolders[folderIdx];
// - by vscode.workspace.findFiles
for (let patternIdx = 0; patternIdx < matchTestsGlobPatterns.length; patternIdx++) {
const currentPattern = matchTestsGlobPatterns[patternIdx];
const pattern = new vscode.RelativePattern(
folder.uri.fsPath,
currentPattern
);
const files = await vscode.workspace.findFiles(
pattern,
'**/node_modules/**'
);
testFilesUris.push(...files);
}
console.log('by [vscode.workspace.findFiles]', testFilesUris.length);
// - by npm Glob
var glob = require('glob');
for (let patternIdx = 0; patternIdx < matchTestsGlobPatterns.length; patternIdx++) {
const currentPattern = matchTestsGlobPatterns[patternIdx];
const files: any[] = await new Promise((resolve, reject) => {
glob(
currentPattern,
{
absolute: true,
cwd: folder.uri.fsPath,
ignore: ['**/node_modules/**']
},
function (err: Error, files: any[]) {
if (err) {
return reject(err);
}
resolve(files);
}
);
});
glob_testFilesUris.push(...files);
}
console.log('by [npm Glob]', glob_testFilesUris.length);
}
// #todo: remove duplicates.
return testFilesUris;
}
The example console output of this function for some project is:
by [vscode.workspace.findFiles] 0
by [npm Glob] 45
Project structure:
rootFolder
src
__tests__
files.test.ts
...
utils
array.test.ts
...
So my question is how do I call vscode.workspace.findFiles to get correct results, or is there known problem with this function?
I have found some kind of answer to the question.
The problem is ?(x) in patterns. The vscode.workspace.findFiles does not work with this pattern as other packages do. If remove it from mentioned glob patterns they work except the .jsx | .tsx files are ommited.
After deep dive into vscode github's issues I have learned (here) that vscode.workspace.findFiles does not support extended patterns like ?(patterLike)

How to create a gulp file with reusable functions - Multiple Watch points & Multiple Output destinations

Goal is to use this Gulp file to execute 'n' number of different source & destinations.
How can we pass the arguments(source, destination) so that the CSS-Generator task is accepting those source & destinations and giving out the separate output files.
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
var paths = {
styles: {
src1: "scss/slider-one/index.scss",
src2: "scss/slider-two/index.scss"
dest1: "slider-one",
dest2: "slider-two"
}
};
function style1() {
return (
gulp
.src(paths.styles.src1)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest1))
);
}
exports.style1 = style1;
function style2() {
return (
gulp
.src(paths.styles.src2)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest2))
);
}
exports.style2 = style2;
function watch() {
style1();
style2();
gulp.watch("scss/slider-one/*.scss", style1);
gulp.watch("scss/slider-two/*.scss", style2);
}
exports.watch = watch
Your source is scss/slider-one/index.scss & destination is slider-one and watch is scss/slider-one/*.scss.
slider-one is common in source, destination & watch.
So you can define the paths array as ["slider-one","slider-two"]
And you are calling the style1 & style2 as the callback of watch function. So you can club that and define that in one function.
And call that function inside for loop with parameters (source,destination,watch).
Full Code:
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
function runGulpSass(src,dest,watch) {
gulp.watch(watch, function() {
return gulp.src(src)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(dest))
});
}
exports.runGulpSass = runGulpSass;
function startGulp() {
var paths = ["slider-one","slider-two"];
for(var i=0;i<paths.length;i++) {
runGulpSass("scss/"+paths[i]+"/index.scss",paths[i],"scss/"+paths[i]+"/*.scss")
}
}
exports.watch = startGulp
[Edit] If there is no common value in source, destination & watch :
Define the paths array like this :
var paths = [
["scss/slider-one/index.scss","css/slider-one","slider-one/*.scss"],
["scss/slider-two/index.scss","css/slider-two","slider-two/*.scss"]
];
And set the runGulpSass function parameter like this :
runGulpSass(paths[i][0],paths[i][1],paths[i][2])

Resources