Environment variables in manifest.json - Chrome Extension - reactjs

Is it possible to set environment variables in the manifest.json file of a Chrome Extension?

Like wOxxOm said, I used webpack to proccess manifest.json.
In my case, I needed to set version automatically on manifest file.
I added to webpack script:
plugins: [
new CopyWebpackPlugin([
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modify(content)
}
}
]),
]
And the modify function replaces version on file for the parameter:
function modify(buffer) {
var manifest = JSON.parse(buffer.toString());
let argv = process.argv[2];
if (argv) manifest.version = argv.split("=")[1];
let manifest_JSON = JSON.stringify(manifest, null, 2);
return manifest_JSON;
}
So, I build like "yarn build --version=x.x" and webpack do what I need.
PS: if you're going to use this, remember to change:
the manifest.json directory, if necessary;
the value in the modify function, in my case it was version

As the OP has mentioned in her answer, using the copy-webpack-plugin in the webpack.config.js file is the way to go if you're building your Chrome Extension with React. However, if your React app is based on create-react-app, directly editing the webpack.config.js file (which is located in node_modules/react-scripts/config) is not recommended.
In such a case, use craco, which is an npm package that can be used to customize an app based on create-react-app. Here's how you do it:
Install craco into your project using npm i #craco/craco.
Install copy-webpack-plugin as a dev-dependency in your project using npm i --save-dev copy-webpack-plugin.
Let's suppose we're creating a development and a production build of our Chrome Extension. Let's also suppose we've already assigned "version": "0.1.0" in our Chrome Extension's manifest.json. Depending on the build type, we'd like to assign accordingly the version_name field in our Chrome Extension's manifest.json, e.g., "version_name": "0.1.0 dev" for development and "version_name": "0.1.0" for production. In your React app's package.json, introduce two fields (the script names can be whatever you wish) as follows:
"scripts": {
...
"build-dev": "CRX_ENV=dev craco build", // or "set CRX_ENV=dev&& craco build" in the case of Windows
"build-prod": "CRX_ENV=prod craco build", // or "set CRX_ENV=prod&& craco build" in the case of Windows
...
}
Create a new file called craco.config.js in the root of your project. As per your need, do something similar to the following in the craco.config.js file:
const CopyPlugin = require("copy-webpack-plugin")
module.exports = {
webpack: {
plugins: [
new CopyPlugin({
patterns: [
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modifyManifest(content)
},
},
],
}),
],
},
}
function modifyManifest(buffer) {
const manifest = JSON.parse(buffer.toString())
if (process.env.CRX_ENV === "dev") {
manifest.version_name = `${manifest.version} dev`
} else if (process.env.CRX_ENV === "prod") {
manifest.version_name = `${manifest.version}`
}
const manifestJson = JSON.stringify(manifest, null, 2)
return manifestJson
}
Run npm run build-dev. It will create a folder called build in your project root. This build folder is your unpacked Chrome Extension, which you can load into Chrome using the "Load unpacked" button on the chrome://extensions page. Once loaded, you should be able to see 0.1.0 dev as the version name of your Chrome Extension.
Delete the build folder created from the previous step and run npm run build-prod, and repeat the same steps. You should be able to see 0.1.0 as the version name of your Chrome Extension on the chrome://extensions page.

Related

Unable to use $npm_package_version when deploying to Netflify

I have a create-react-app (CRA) deployed to Netlify and I copied over my .env file contents over to Netlify's environment variables build settings. I added REACT_APP_VERSION as the key with $npm_package_version as the value.
But when the app got deployed, this particular environment variable is being shown as a literal string. It doesn't get evaluated to 0.1.0 as what is defined on my package.json file. All my other environment variables work just fine because they are string literals. How do I fix this?
I was able to fix this by injecting environment variables using local build plugins.
Here's my file structure:
> project
> plugins
> netlify
> env
- index.js
- manifest.yml
- package.json ---> only for the plugin (to define as a module)
...
- netlify.toml
- package.json ---> where I need to grab values from
...
And these are the contents of the files:
index.js
export const onPreBuild = function ({ netlifyConfig, packageJson }) {
netlifyConfig.build.environment.REACT_APP_NAME = packageJson.name;
netlifyConfig.build.environment.REACT_APP_VERSION = packageJson.version;
};
manifest.yml
name: netlify-env
package.json (inside of plugins/netlify/env directory)
{
"name": "netlify-env",
"version": "1.0.0",
"type": "module"
}
netlify.toml
[[plugins]]
package = "/plugins/netlify/env"

How to add extra resources files in production in electron using electron-forge

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.

Upgrading react-scripts gives error on running react-scripts start

After updating react-scripts to version 3.4.0 and on running react-scripts start in windows I get this error:
Must use import to load ES Module: C:\Users\myUser\Desktop\Projects\myproject\frontend\src\setupProxy.js
require() of ES modules is not supported.
require() of C:\Users\myUser\Desktop\Projects\myproject\frontend\src\setupProxy.js from C:\Users\myUser\Desktop\Projects\myproject\frontend\node_modules\react-scripts\config\webpackDevServer.config.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename setupProxy.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\myUser\Desktop\Projects\myproject\frontend\package.json.
And this is the file setupProxy:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
const proxyTarget = process.env.REACT_APP_API || 'http://localhost:8089';
console.log(`proxying /backend/api/* to ${proxyTarget}/backend/*`);
app.use(proxy('/backend/api', { target: proxyTarget}));
};
Why do I get this error after upgrading react-scripts, and it only displays on windows, if I run the same command on mac, then I don't get this error. How can I fix this for windows?

React analyze bundle size

I have a question - how to analyze bundle size?
I want to get informations how bundle files change in case i will push the commit in gitlab.
I was looking for something like danger.js but it probably doesn't support gitlab.
You can use this script to analyze, without ejecting create-react-app
Put analyze.js in root of your project ( where the package.json is located )
npm install progress-bar-webpack-plugin
npm install webpack-bundle-analyzer
analyze.js
process.env.NODE_ENV = 'production';
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const webpackConfigProd = require('react-scripts/config/webpack.config')('production');
// this one is optional, just for better feedback on build
const chalk = require('chalk');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const green = text => {
return chalk.green.bold(text);
};
// pushing BundleAnalyzerPlugin to plugins array
webpackConfigProd.plugins.push(new BundleAnalyzerPlugin());
// optional - pushing progress-bar plugin for better feedback;
// it can and will work without progress-bar,
// but during build time you will not see any messages for 10-60 seconds (depends on the size of the project)
// and decide that compilation is kind of hang up on you; progress bar shows nice progression of webpack compilation
webpackConfigProd.plugins.push(
new ProgressBarPlugin({
format: `${green('analyzing...')} ${green('[:bar]')}${green('[:percent]')}${green('[:elapsed seconds]')} - :msg`,
}),
);
// actually running compilation and waiting for plugin to start explorer
webpack(webpackConfigProd, (err, stats) => {
if (err || stats.hasErrors()) {
console.error(err);
}
});
Now simply put node ./analyze.js in the package.json scripts
"scripts": {
.....
"analyze": "node ./analyze.js"
},
after that run npm run analyze
You can also accomplish this using webpack stats json file, supported by create-react-app and webpack-bundle-analyzer.
When running your build with create-react-app, add the --stats flag:
yarn build --stats
This will create a build/bundle-stats.json file, with webpack stats, allowing you to use the webpack-bundle-analyzer CLI to analyze this stats.
yarn run webpack-bundle-analyzer build/bundle-stats.json
reference:
https://www.npmjs.com/package/webpack-bundle-analyzer#user-content-usage-as-a-cli-utility
tested with CRA latest version at the time: v4
You can use and configure webpack-bundle-analyzer library and use it in your React App WITHOUT EJECTING
Add some dependencies by executing npm install --save-dev progress-bar-webpack-plugin webpack-bundle-analyzer
Create a new folder named scripts at the root of your React App.
Create a new file analyze_build_bundle.js in the scripts folder and add the below code in that file
// script to enable webpack-bundle-analyzer
process.env.NODE_ENV = 'production';
const webpack = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const webpackConfigProd = require('react-scripts/config/webpack.config')(
'production'
);
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
webpackConfigProd.plugins.push(new BundleAnalyzerPlugin());
webpackConfigProd.plugins.push(
new ProgressBarPlugin({
format: `analyzing... [:bar] [:percent] [:elapsed seconds] - :msg`,
})
);
// actually running compilation and waiting for plugin to start explorer
webpack(webpackConfigProd, (err, stats) => {
if (err || stats.hasErrors()) {
console.error(err);
}
});
Add the analyze-build-bundle command in your package.json file to run the webpack-bundle-analyzer as below:
"scripts": {
"analyze-build-bundle": "node scripts/analyze_build_bundle.js",
"start": "react-scripts start",
.....
...
}
Now execute command npm run analyze-build-bundle. This will build your app and then start the analyzer local server and you should be able to see the screen as shown in below image

How to pass output path to webpack as parameter using npm?

I have a Angular application that uses Webpack as module bundler. In my package.json, I have the following scripts:
"scripts": {
"start": "webpack",
"start-in-war": "??????"
}
Also, this is the output portion of my webpack.config.js
output: {
path: __dirname + "/dist/",
filename: "app.js"
}
Since I also want this application to be packaged into a WAR file with my backend service, I need to pass that path field as parameter, so I will mantain both configurations: the default that is more development-friendly (I don't have to deploy the application anytime I make a client change) and the one I will ultimately use (that would be the "start-in-war" parameter).
How can I achieve that?
Note: The start-in-war script is not gonna be used just for production, also development.

Resources