webpack config with optional usage of BundleAnalyzerPlugin - reactjs

I'm using webpack for a React project and would like to include the WebpackBundleAnalyzer, but only when explicitly specified in the npm script (e.g., npm run build --withReport true). By default, I don't want it to run.
My build script in package.json is straightforward:
"build": "webpack --mode production",
As are are the relevant snippets from my webpack.config.js:
...
const withReport = process.env.npm_config_withReport || 'false';
...
plugins: [
...
withReport ? new BundleAnalyzerPlugin() : '',
],
...
My thought is that withReport will be false unless I specify otherwise (e.g., npm run build --withReport true), thus the BundleAnalyzer will not execute if I leave that off (npm run build).
Instead, the analyzer executes even if I don't specify --withReport. What am I missing?

I fixed this by making a couple changes to my webpack.config.js.
First I changed the way I declare withReport. Then I changed the way I instantiate BundleAnalyzerPlugin, to instead use concat after the other plugins:
...
const withReport = process.env.npm_config_withReport ? true : false;
...
plugins: [
...
].concat(withReport ? [new BundleAnalyzerPlugin()] : []),
...

Related

Create React App with TypeScript and NPM Link: Enums causing Module parse failed

I have a basic create-react-app TypeScript project (client). Just directory up, I have a server and a shared folder. Inside the shared folder I have a number of interfaces and enums that I share between the server and the client.
I wish to link this shared folder to both the client and server packages.
First, I went to shared and ran $ yarn link and then ran $ yarn link shared from both the client and the server folders.
The server is as happy as can be, and for the most part the client is too. However, as soon as I use one of the enums from the shared directory in the client, I get an error:
../shared/src/models/Roles.ts 4:0
Module parse failed: The keyword 'enum' is reserved (4:0)
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
| $RefreshSetup$(module.id);
|
> enum Roles {
| RW_ORG = "rw_org", // can modifiy organization and it's users, nothing else
I'm importing it like so:
import {Roles} from "shared";
but have tried numerous other ways as well.
I'm exporting it from the shared index.ts like so
import Roles from "./models/Roles";
export type {
// all of my interfaces
};
export { Roles }
All of my interfaces are usable, so I don't understand. What the hell is going on here?
Well, it turns out that these errors are all cause by create-react-app's default webpack.config.js. If you navigate to code node_modules/react-scripts/config/webpack.config.js you fill find a line include: paths.appSrc which basically limits Babel to the src/ folder of the react app itself.
That means, if you've yarn linked a folder outside of it, Babel will not transpile it to normal JS, and thus React cannot use it.
There are two hacky solutions, but I would like a better one.
Manually (or via a build script) delete the include: paths.appSrc line from react-scripts every time you install a node module
Make a script that copies the external directory into your React src directory every time the external directory is modified.
I really wish there were an official way around this...
Based on #foxtrotuniform6969's answer, i created a #cracro/craco configuration that gets rid of the misbehaving setting by itself.
module.exports = {
webpack: {
configure: (webpackConfig) => ({
...webpackConfig,
module: {
...webpackConfig.module,
rules: webpackConfig.module.rules.map((rule) => {
if (!rule.oneOf) return rule;
return {
...rule,
oneOf: rule.oneOf.map((ruleObject) => {
if (
!new RegExp(ruleObject.test).test('.ts') ||
!ruleObject.include
)
return ruleObject;
return { ...ruleObject, include: undefined };
}),
};
}),
},
}),
},
};
https://gist.github.com/PhilippMolitor/00f427d12a9c5bca84309058d88846b7
It is possible to automatically remove the include path setting mentioned in the other answer using react-app-rewired.
The following config-overrides.js works for react-scripts:4.0.3 and causes babel to also transpile files in node-modules.
// config-overrides.js
module.exports = function override(config, env) {
// This line might break with other react-script versions
delete config.module.rules[1].oneOf[2].include
return config
}
The other answers to this question suggest removing the include in react-scripts' webpack.config (either with craco or react-app-rewired). I found this worked with yarn start, but when I made a production build with yarn build I got the error Uncaught ReferenceError: exports is not defined at runtime.
Instead of removing the include, I had to add the other project's src in addition to the existing src directory.
Here's my config-overrides.js to be used with react-app-rewired.
For react-scripts 4:
const path = require("path");
module.exports = function override(config) {
// See https://stackoverflow.com/questions/65893787/create-react-app-with-typescript-and-npm-link-enums-causing-module-parse-failed.
config.module.rules[1].oneOf[2].include = [
path.join(__dirname, './src'),
path.join(__dirname, '../backend/src')
];
return config
}
For react-scripts 5:
const path = require("path");
module.exports = function override(config) {
// See https://stackoverflow.com/questions/65893787/create-react-app-with-typescript-and-npm-link-enums-causing-module-parse-failed.
config.module.rules[1].oneOf[3].include = [
path.join(__dirname, './src'),
path.join(__dirname, '../backend/src')
];
return config
}
My craco config, does the same thing as Phil Mo's version as far as I can tell but is easier to understand
module.exports = {
webpack: {
configure: (webpackConfig) => {
webpackConfig.module.rules[0].oneOf.find(
({ test: t }) =>
t != null &&
!Array.isArray(t) &&
t.toString().includes('ts')
).include = undefined
return webpackConfig
}
}
}

How can I disable chunk(code splitting) with webpack4?

I created react project with : yarn create react-app. I'm using webpack 4.29.6, react 16.8.6.
I want to disable code splitting because I want just one 'main.js' file in build/static/js folder. (I already removed hash from their names.)
I tried:
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
}),
and
splitChunks: {
chunks: 'all',
name: false,
cacheGroups: {
default:false
}
}
but these solutions give me these files:
build
/static
/js
-2.chunk.js
-2.chunk.js.map
-main.chunk.js
-main.chunk.js.map
-runtime~main.js
-runtime~main.js.map
I think runtime~main.js file and .map file are just okay, but I want the exact 'main.js' file without chunk, without 2.chunk.js. How can I disable default code splitting of webpack 4?
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
]
Try if this works. Install this manually LimitChunkCountPlugin
https://webpack.js.org/plugins/limit-chunk-count-plugin/
If you created your project with create-react-app and haven't yet ejected, it appears you have two options currently available:
Option 1 - Create a custom build script
First, install the package rewire as a dependency:
npm install rewire
Create a scripts folder, inside create a new file and give it a name e.g., build-non-split.js, then add:
const rewire = require('rewire');
const defaults = rewire('react-scripts/scripts/build.js');
let config = defaults.__get__('config');
config.optimization.splitChunks = {
cacheGroups: {
default: false,
},
};
config.optimization.runtimeChunk = false;
Modify package.json, inside "scripts" and replace build with:
"build": "node ./scripts/build-non-split.js",
Finally, run npm run build or yarn build
Option 2 - Install the package react-app-rewire-disable-chunks
Note: If you go with this option, don't forget to replace the build script with react-app-rewired. Like this:
"build": "react-app-rewired build",
Source: Disabling code splitting in CRA2 #5306

How to configure react-script so that it doesn't override tsconfig.json on 'start'

I'm currently using create-react-app to bootstrap one of my projects. Basically, I'm trying to set up paths in tsconfig.json by adding these to the default tsconfig.json generated by create-react-app:
"baseUrl": "./src",
"paths": {
"interfaces/*": [
"common/interfaces/*",
],
"components/*": [
"common/components/*",
],
},
However, every time I run yarn start which basically runs react-scripts start, it deletes my changes and generates the default configurations again.
How can I tell create-react-app to use my custom configs?
I was able to do this by using advice from this issue.
Put the configuration options react scripts likes to remove in a separate file (e.g. paths.json) and reference it from tsconfig.json via the extends directive.
paths.json:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"interfaces/*": [ "common/interfaces/*"],
"components/*": [ "common/components/*"],
}
}
}
tsconfig.json
{
"extends": "./paths.json"
...rest of tsconfig.json
}
Create React App does not currently support baseUrl. However there is a workaround...to setup baseUrl for both webpack and the IDE you have to do the following:
Create a .env file with the following code:
NODE_PATH=./
Create a tsconfig.paths.json file with the following code inside:
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"src/*": ["*"]
}
}
}
Add the following line to tsconfig.json
{
"extends": "./tsconfig.paths.json",
...
}
You can't and I am unsure when you will be able to. I have been trying to use baseUrl and paths so I can avoid relative imports but as you can see they are intentionally removing certain values. The "(yet)" is encouraging but (sigh) who knows when they will officially be supporting it. I recommend subscribing to this github issue to be alerted if/when this changes.
The following changes are being made to your tsconfig.json file:
- compilerOptions.baseUrl must not be set (absolute imports are not supported (yet))
- compilerOptions.paths must not be set (aliased imports are not supported)
If you are using react-scripts 4.0.0 like me then all you need to do is remove the line (around line 160 on my end):
paths: { value: undefined, reason: 'aliased imports are not supported' }
from the file node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
I was able to straight up add my baseUrl and paths config to my tsconfig.json file like so:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#domain/*": ["../src/domain/*"],
},
}
}
and finally compile and move on with my life.
Per usual, YMMV. Please test your stuff. This is obviously a hack but it worked for me so I'm posting here in case it helps someone.
Here's a patch if you feel like sharing with your team:
diff --git a/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js b/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
index 00139ee..5ccf099 100644
--- a/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
+++ b/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
## -156,7 +156,8 ## function verifyTypeScriptSetup() {
: 'react',
reason: 'to support the new JSX transform in React 17',
},
- paths: { value: undefined, reason: 'aliased imports are not supported' },
+ // Removed this line so I can add paths to my tsconfig file
+ // paths: { value: undefined, reason: 'aliased imports are not supported' },
};
Edit
Per #Bartekus thoughtful suggestion in the comments thread I'm adding information on the package I use when I need to add (possibly) temporary changes like these to an npm package: patch-package
The package essentially provides a way to make changes to a package in a cleaner way. Especially when you consider collaboration it becomes very cumbersome to directly change an npm file and move on. The next time you update that package or even when you start developing in a new machine and run npm install your changes will be lost. Also, if you have teammates working on the same project they would never inherit the changes.
In essence you go through the following steps to patch a package:
# fix a bug in one of your dependencies
vim node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
# run patch-package to create a .patch file
npx patch-package react-scripts
# commit the patch file to share the fix with your team
git add patches/react-scripts+4.0.0.patch
git commit -m "Enable aliased imports in react-scripts"
Next time someone checks out the project and installs it, the patch will be applied automatically due to a post-install script you add during set up:
"scripts": {
+ "postinstall": "patch-package"
}
See up to date instructions in the package's documentation
I had a similar issue to this general problem (CRA overwrites "noEmit": false in my tsconfig.json of a React library I'm working on where I have two separate builds, one for local development, and another to build the production library with typings). Simple solution: use sed in a postbuild script in the package.json. For example: In-place edits with sed on OS X .
{
...
"scripts": {
...
"postbuild": "sed -i '' 's/{THING CRA IS REPLACING}/{WHAT YOU ACTUALLY WANT}/g' tsconfig.json # CRA is too opinionated on this one.",
...
}
...
}
This approach, however, is not cross-platform (unlike how rimraf is the cross-platform alternative to rm -rf).
For me, the problem was with VSCode using an older version of typescript (4.0.3), while the typescript version shipped with the project is (4.1.2).
The following did the trick for me:
Go to the command palette CTRL+Shift+P.
Choose "TypeScript: Select a TypeScript Version...".
Choose "Use workspace Version".
On Botpress (with react-scripts 4.0.3), we use a combination of 2 tricks to use paths without ejecting or patching the code. As Glenn and Microcipcip said, the first step is to extend the tsconfig.json file
tsconfig.path.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"~/*": ["src/*"],
"common/*": ["../bp/src/common/*"]
}
}
}
tsconfig.json
{
...
"extends": "./tsconfig.paths.json"
}
Then to make it work in the background, use the package react-app-rewired. It allows to make slight adjustments to the webpack configuration without actually ejecting CRA.
config-overrides.js
module.exports = {
webpack: (config, env) => {
config.resolve.alias['common'] = path.join(__dirname, '../bp/dist/common')
config.resolve.alias['~'] = path.join(__dirname, './src')
}
}
To see the full code, you can check the github repository https://github.com/botpress/botpress/tree/master/packages/ui-admin
For macOS this workaround should work.
package.json
"scripts": {
"start": "osascript -e 'tell app \"Terminal\" to do script \"cd $PATH_TO_REACT_APP && node ./setNoEmitFalse\"' && react-scripts start",
...
},
...
setNoEmitFalse.js
const fs = require('fs');
const { sleep } = require('sleep')
const path = './tsconfig.json'
const run = async () => {
sleep(2)
const tsconfig = fs.readFileSync(path, 'utf-8');
const fixed = tsconfig.replace('"noEmit": true', '"noEmit": false');
fs.writeFileSync(path, fixed)
}
run()
The execution of the javascript file in a separate terminal (osascript) provides the normal output for react-scripts in the original terminal.
Go to node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js and replace
const compilerOptions = {
...
};
by
const compilerOptions = { };

Set externals according to NODE_ENV

I'm trying to set an external config in my webpack according to the NODE_ENV.
Here's my script code from package.json:
"scripts": {
"build": "set NODE_ENV=production && webpack --mode production",
"start": "webpack-dev-server --hot --mode development"
},
Then in my webpack.config.js I have the following code:
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
apiUrl: "."
} : {
apiUrl: "http://localhost:3000"
})
},
Somehow this doesn't work. I always get the "false" (localhost) as value. I'm 100 % sure process.env.NODE_ENV is set since first of all, I log it at the beginning of the file (console.log(process.env.NODE_ENV)) and it gives me "production" as answer.
Second, I tried to create another config like:
externals: {
'Test': {"mytest": process.env.NODE_ENV } ...
and this sets mytest to "production" ....
I have no idea why this doesn't work, I copied the code from stackoverflow (How to store Configuration file and read it using React).
I tried everything... I wrapped around the JSON.stringify around other parts, I tried to debuff as good as I can. Its now the 4th hour I spend on this problem and I think its a good moment to ask here for some advise.
If you can help me solve this problem, I would be really thankful!
Have a nice day.

How to add sourcemap in React Native for Production?

I received error log like the following while the app crashed:
Fatal Exception: com.facebook.react.modules.core.JavascriptException:
onSelect index.android.bundle:20:7148 onPress
index.android.bundle:20:2435
But it's not really helpful for me to trouble shoot. How could I enable source map so that I could track down where the issue is ?
UPDATE 2018
https://docs.expo.io/versions/latest/guides/using-sentry.html Looks promising !
For source mapping here is the way I go about it:
In my bundle command for my production build I tell it to generate a source map:
iOS:
react-native bundle --platform ios --entry-file index.ios.js --dev false --bundle-output ./ios/main.jsbundle --assets-dest ./ios --sourcemap-output ./sourcemap.js
Android - I had to actually modify the android/app/react.gradle file to get source maps generating on release compile. There might be an easier way but basically you find where it builds up the bundle command in the bundleReleaseJsAndAssets method and add the source map bit to it:
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine "cmd","/c", "react-native", "bundle", "--platform", "android", "--dev", "false", "--entry-file",
entryFile, "--bundle-output", jsBundleFileRelease, "--assets-dest", resourcesDirRelease, "--sourcemap-output", file("$buildDir/../../../sourcemap.js")
} else {
commandLine "react-native", "bundle", "--platform", "android", "--dev", "false", "--entry-file",
entryFile, "--bundle-output", jsBundleFileRelease, "--assets-dest", resourcesDirRelease, "--sourcemap-output", file("$buildDir/../../../sourcemap.js")
}
The output path looks a bit odd but that puts it at your root level (same spot as iOS. I wanted it that way. You can obviously put it anywhere).
Then once you have an error with the line number that means nothing you run it through the "source-map" NPM package. You could probably get very elaborate with your approach but I simply went with:
var sourceMap = require('source-map');
var fs = require('fs');
fs.readFile('./sourcemap.js', 'utf8', function (err, data) {
var smc = new sourceMap.SourceMapConsumer(data);
console.log(smc.originalPositionFor({
line: 16,
column: 29356
}));
});
Where line and column should be replaced withe line and column number from your example output above.
This obviously works best if you have the source maps stored somewhere as the line and column numbers change from build to build as your code changes. It should get pretty close though if you can use you source control setup of choice to go back to the commit that was used to build the app in question and re-generate the bundle with the additional bits to the command to generate the source map.
Android inspired by #chetstone's answer
Starting on v0.32 for android, you can modify your android/app/build.gradle to accomplish this.
Look for the line
apply from: "../../node_modules/react-native/react.gradle"
Just above this, you will see something like:
project.ext.react = [
entryFile: "index.js",
]
Modify it to match the following
project.ext.react = [
entryFile: "index.js",
extraPackagerArgs: ["--sourcemap-output", file("$buildDir/../../../sourcemap.android.js")]
]
On iOS
Go to your build phases in Xcode for the "Bundle React Native code and images" phase and add:
export EXTRA_PACKAGER_ARGS="--sourcemap-output sourcemap.ios.js"
As noted, there's no obvious way to generate the sourcemap file for React Native on iOS. The bundle command is called from react-native-xcode.sh, and there's no provision to add parameters to the bundle command line. But I found a clean way to do it.
react-native-xcode.sh uses the environment variable BUNDLE_CONFIG to specify a config file. If you create an empty config file it has no effect, and then you can add additional CLI parameters.
Create an empty config file.
touch null_config
Set BUNDLE_CONFIG with your config file, and piggyback the --sourcemap-output parameter.
export BUNDLE_CONFIG="null_config --sourcemap-output ./sourcemap.js.map"
When you build, the file sourcemap.js.map will be created.
This is only for iOS.
step 1: Generate sourcemap.js file by using following command.
add this line in package.json file
"bundle:ios": "mkdir -p ios/{Bundle,source-map}; react-native bundle --platform ios --entry-file index.js --dev false --bundle-output ios/Bundle/main.jsbundle --assets-dest ios/Bundle --sourcemap-output ios/source-map/sourcemap.js"
Run this command, it will create sourcemap.js file under $PROJECT_DIR/ios/source-map/ folder
$ yarn bundle:ios
Step 2: Create a file sourcemap-decoder.js under $PROJECT_DIR/ios/source-map/
$ cd ios/source-map/
$ touch sourcemap-decoder.js
Content of sourcemap-decoder.js is
const sourceMap = require('source-map'); //(install- npm i source-map)
const fs = require('fs');
const path = require('path');
fs.readFile(path.resolve(__dirname, 'sourcemap.js'), 'utf8', async (err, data) => {
if (err) {
console.log('err', err,);
}
const consumer = await new sourceMap.SourceMapConsumer(JSON.parse(data));
console.log(consumer.originalPositionFor({
line: 1408,
column: 7762
}));
});
Step 3: execute the script for decoding
$ node ios/source-map/sourcemap-decoder.js

Resources