How to set global property for react using esbuild - reactjs

According to the docs using define is the suggested way of setting the env properties for a build.
When I run my app with I get a process is not defined error.
My esconfig is as follows:
await build({
entryPoints: ['./src/index.tsx'],
outdir: './build',
bundle: true,
incremental: true,
metafile: true,
target: 'es6',
loader: { '.png': 'file' },
minify: !dev,
sourcemap: 'inline',
define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') },
plugins: [
sassPlugin(),
svg(),
copy({
resolveFrom: 'cwd',
assets: {
from: ['./public/*'],
to: ['./build2/*'],
},
}),
copy({
resolveFrom: 'cwd',
assets: {
from: ['./public/images/*'],
to: ['./build2/images/*'],
},
}),
],
watch: dev
? {
onRebuild: (error) => {
if (error) {
console.error(error);
} else {
console.log('rebuild done');
}
},
}
: false,
});
I'm also open to other ways of setting global properties to control the configuration.

I've resorted to writing a config/env file before the build starts.
My react app then just needs to know where the env file is located.
const config: IEnv = {
ENV: process.env.NODE_ENV ? process.env.NODE_ENV : 'development',
USE_EMU: process.env.USE_EMU === '1' ? true : false,
USE_DEV: process.env.USE_DEV === '1' ? true : false,
VERSION: process.env.VERSION ? process.env.VERSION : 'dev',
};
fs.writeFileSync('src/env.json', JSON.stringify(config), { encoding: 'utf8' });

You are getting process is not defined error because you actually do not define process in define option, you do define process.env.NODE_ENV.
It may be counterintuitively but it is how define option is used. It doesn't actually defines variable and just replaces all tokens that look like define key with corresponding value.

Related

Webpack 5 module federation error handling

I've a micro frontends running on monorepo using nx CLI where in the host application I'm using module federation to get the remoteEntry.js files from all the micro frontends and serve them as components per route.
I've error boundary which works perfect on dev / staging / production environment and displays 404 page when the remoteEntry is not fetched / crashed for some reason and it works as expected.
But when I want to run unit tests on the shell application to test its functionality and I'm running only the shell application, for some reason I'm receiving errors from webpack saying the following:
Loading script failed.
(error: http://localhost:3107/remoteEntry.js)
Which is expected, because I didn't run any of the micro frontends.
What I want to achieve is that I will be able to run only the shell application locally and get the 404 page also on local without having this error, in other words - I want to handle the errors when the micro frontends are not live.
Any suggestions how can I achieve that?
webpack file on the shell application:
const nrwlConfig = require('#nrwl/react/plugins/webpack.js');
const { ModuleFederationPlugin } = require('webpack').container;
const deps = require('../../package.json').dependencies;
const { remoteEntries } = require('./remoteEntries');
const EnvType = {
LOCAL: 'local',
PLAYGROUND: 'playground',
DEVELOPMENT: 'development',
STAGING: 'staging',
PRODUCTION: 'production',
};
module.exports = (config) => {
nrwlConfig(config);
config.optimization.runtimeChunk = 'single';
return {
...config,
plugins: [
...config.plugins,
new ModuleFederationPlugin({
name: 'hostApp',
filename: 'remoteEntry.js',
remotes: {
app1: `app1#${getRemoteEntryUrl(remoteEntries.APP1)}`,
app2: `app2#${getRemoteEntryUrl(remoteEntries.APP2)}`,
app3: `app3#${getRemoteEntryUrl(
remoteEntries.APP3
)}`,
app4: `app4#${getRemoteEntryUrl(
remoteEntries.APP4
)}`,
app5: `app5#${getRemoteEntryUrl(remoteEntries.APP5)}`,
app6: `app6#${getRemoteEntryUrl(
remoteEntries.APP6
)}`,
app7: `app7#${getRemoteEntryUrl(
remoteEntries.APP7
)}`,
},
shared: {
...deps,
react: {
singleton: true,
eager: true,
requiredVersion: deps.react,
},
'react-dom': {
singleton: true,
eager: true,
requiredVersion: deps['react-dom'],
},
},
}),
],
};
};
const getRemoteEntryUrl = (entry) => {
const { NODE_ENV } = process.env || EnvType.DEVELOPMENT;
if (NODE_ENV !== EnvType.LOCAL) {
return entry.remoteEntries[NODE_ENV];
}
return `http://localhost:${entry.localPort}/remoteEntry.js`;
};

Webpack Module Federation loads chunks from wrong URL

I am building a project with webpack module federation with the following setup:
React host (running on localhost:3000)
Angular Remote 1 (running on localhost:4201)
Angular Remote 2 (running on localhost:4202)
The goal is to get both remotes working. If I only run one of the and remove the other it is working perfectly.
The issue I am facing is that when the remotes are loaded, __webpack_require__.p is set by one of the remotes' script and therefore the other remote's chunk is loaded from the wrong url.
Here is the error I get:
My module federation config is the following:
React host:
.
.
.
new ModuleFederationPlugin({
name: "react_host",
filename: "remoteEntry.js",
remotes: {
angular_remote_1: "angular_remote_1#http://localhost:4201/angular_remote_1.js",
angular_remote_2: "angular_remote_2#http://localhost:4202/angular_remote_2.js"
},
exposes: {},
shared: {
...deps,
react: {
singleton: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
requiredVersion: deps["react-dom"],
},
},
}),
.
.
.
Angular Remote 1
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
output: {
publicPath: "auto",
uniqueName: "angular_remote_1",
scriptType: "text/javascript"
},
optimization: {
runtimeChunk: false
},
experiments: {
outputModule: true
},
plugins: [
new ModuleFederationPlugin({
name: "angular_remote_1",
library: { type: "var", name: "angular_remote_1" },
filename: "angular_remote_1.js",
exposes: {
'./angularRemote1': './src/loadAngularRemote1.ts',
},
shared: ["#angular/core", "#angular/common", "#angular/router"]
})
],
};
Angular Remote 2
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
output: {
publicPath: "auto",
uniqueName: "angular_remote_2",
scriptType: "text/javascript"
},
optimization: {
runtimeChunk: false
},
experiments: {
outputModule: true,
},
plugins: [
new ModuleFederationPlugin({
name: "angular_remote_2",
library: { type: "var", name: "angular_remote_2" },
filename: "angular_remote_2.js",
exposes: {
'./angularRemote2': './src/loadAngularRemote2.ts',
},
shared: ["#angular/core", "#angular/common", "#angular/router"]
})
],
};
Thins I have tried so far:
Playing around with public path (between auto and hardcoded)
Setting a custom chunkLoadingGlobal for both remotes (not the host)
The exact reproduction of this issue can be found here: https://github.com/BarniPro/react-host-angular-remotes-microfrontend
Any help is greatly appreciated.
The issue can be solved by setting the topLevelAwait experiment to true in the remotes's webpack.config.js:
experiments: {
topLevelAwait: true,
},
This results in the two remotes loading in sync which prevents the paths from overriding each other.
Another update I had to make was disabling the splitChunks option in the remotes' optimization settings (see SplitChunksPlugin):
optimization: {
runtimeChunk: false, // This is also needed, but was added in the original question as well
splitChunks: false,
}
The Github repo has been updated with the working solution.

How to import a library directly from master branch in react?

https://github.com/danielcaldas/react-d3-graph/issues/276
The question is related to above issue. I tried to update webpack as mentioned in the answers on github but i am constantly getting the same error. I am using create-react-app and typescript.
Module parse failed: Unexpected token (127:33)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| * #returns {Object} - Focus and zoom animation properties.
| */
> _generateFocusAnimationProps = () => {
| const { focusedNodeId } = this.state;
I also tried installing it directly via npm but it is not working and I am getting the same error.
Tried importing like
import { Graph } from "react-d3-graph/src/index";
import { Graph } from "react-d3-graph/src";
import { Graph } from "react-d3-graph";
does not work so I am pretty much sure that the issue is with web pack any help is appreciated.
Webpack
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const safePostCssParser = require('postcss-safe-parser');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
const postcssNormalize = require('postcss-normalize');
const appPackageJson = require(paths.appPackageJson);
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
const useTypeScript = fs.existsSync(paths.appTsConfig);
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
module.exports = function(webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
const publicPath = isEnvProduction
? paths.servedPath
: isEnvDevelopment && '/';
const shouldUseRelativeAssetPaths = publicPath === './';
const publicUrl = isEnvProduction
? publicPath.slice(0, -1)
: isEnvDevelopment && '';
const env = getClientEnvironment(publicUrl);
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
postcssNormalize(),
],
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
return {
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
"./index.jsx"
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
].filter(Boolean),
output: {
// The build folder.
path: isEnvProduction ? paths.appBuild : undefined,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// TODO: remove this when upgrading to webpack 5
futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
// We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
// Prevents conflicts when multiple Webpack runtimes (from different apps)
// are used on the same page.
jsonpFunction: `webpackJsonp${appPackageJson.name}`,
// this defaults to 'window', but by setting it to 'this' then
// module chunks which are built will work in web workers as well.
globalObject: 'this',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
sourceMap: shouldUseSourceMap,
}),
// This is only used in production mode
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
parser: safePostCssParser,
map: shouldUseSourceMap
? {
// `inline: false` forces the sourcemap to be output into a
// separate file
inline: false,
// `annotation: true` appends the sourceMappingURL to the end of
// the css file, helping the browser find the sourcemap
annotation: true,
}
: false,
},
}),
],
splitChunks: {
chunks: 'all',
name: false,
},
runtimeChunk: {
name: entrypoint => `runtime-${entrypoint.name}`,
},
},
resolve: {
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
'react-native': 'react-native-web',
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module),
],
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
},
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
enforce: 'pre',
use: [
{
options: {
cache: true,
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
resolvePluginsRelativeTo: __dirname,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent:
'#svgr/webpack?-svgo,+titleProp,+ref![path]',
},
},
},
],
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
// In development, this will be an empty string.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
isEnvDevelopment && new CaseSensitivePathsPlugin(),
isEnvDevelopment &&
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: publicPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
isEnvProduction &&
new WorkboxWebpackPlugin.GenerateSW({
clientsClaim: true,
exclude: [/\.map$/, /asset-manifest\.json$/],
importWorkboxFrom: 'cdn',
navigateFallback: publicUrl + '/index.html',
navigateFallbackBlacklist: [
new RegExp('^/_'),
new RegExp('/[^/?]+\\.[^/]+$'),
],
}),
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
typescript: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
async: isEnvDevelopment,
useTypescriptIncrementalApi: true,
checkSyntacticErrors: true,
resolveModuleNameModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
resolveTypeReferenceDirectiveModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
tsconfig: paths.appTsConfig,
reportFiles: [
'**',
'!**/__tests__/**',
'!**/?(*.)(spec|test).*',
'!**/src/setupProxy.*',
'!**/src/setupTests.*',
],
silent: true,
// The formatter is invoked directly in WebpackDevServerUtils during development
formatter: isEnvProduction ? typescriptFormatter : undefined,
}),
].filter(Boolean),
node: {
module: 'empty',
dgram: 'empty',
dns: 'mock',
fs: 'empty',
http2: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
performance: false,
};
};
Elaborating my comment. You could do this
Clone the repo to your local file system.
Run the repo's build commands to generate a build. You'll need to see the building instructions from the repo itself. Usually available in README.md or CONTRIBUTING.md.
Then, use either use npm link or npm install to reference the locally built package.

Build performance for webpack 2

I need some help in improving my build times. I upgraded my webpack config file to version 2 but the build times are worse compared to before. It takes atleast 3min to complete the build.
Here's my webpack file
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
require('dotenv').config();
import path from 'path';
import webpack from 'webpack';
import extend from 'extend';
import AssetsPlugin from 'assets-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import bundles from '../src/bundles'
import merge from 'lodash/merge'
import fs from 'fs'
const DEBUG = !process.argv.includes('--release');
const VERBOSE = process.argv.includes('--verbose');
const GLOBALS = {
'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"',
'process.env.MORTGAGE_CALCULATOR_API': process.env.MORTGAGE_CALCULATOR_API ? `"${process.env.MORTGAGE_CALCULATOR_API}"` : null,
'process.env.API_HOST': process.env.BROWSER_API_HOST ? `"${process.env.BROWSER_API_HOST}"` : process.env.API_HOST ? `"${process.env.API_HOST}"` : null,
'process.env.GOOGLE_ANALYTICS_ID': process.env.GOOGLE_ANALYTICS_ID ? `"${process.env.GOOGLE_ANALYTICS_ID}"` : null,
'process.env.OMNITURE_SUITE_ID': process.env.OMNITURE_SUITE_ID ? `"${process.env.OMNITURE_SUITE_ID}"` : null,
'process.env.COOKIE_DOMAIN': process.env.COOKIE_DOMAIN ? `"${process.env.COOKIE_DOMAIN}"` : null,
'process.env.FEATURE_FLAG_BAZAAR_VOICE': process.env.FEATURE_FLAG_BAZAAR_VOICE ? `"${process.env.FEATURE_FLAG_BAZAAR_VOICE}"` : null,
'process.env.FEATURE_FLAG_REALTIME_RATING': process.env.FEATURE_FLAG_REALTIME_RATING ? `"${process.env.FEATURE_FLAG_REALTIME_RATING}"` : null,
'process.env.SALE_RESULTS_PAGE_FLAG': process.env.SALE_RESULTS_PAGE_FLAG ? `"${process.env.SALE_RESULTS_PAGE_FLAG}"` : null,
'process.env.SALE_RELOADED_RESULTS_PAGE_FLAG': process.env.SALE_RELOADED_RESULTS_PAGE_FLAG ? `"${process.env.SALE_RELOADED_RESULTS_PAGE_FLAG}"` : null,
'process.env.TRACKER_DOMAIN': process.env.TRACKER_DOMAIN ? `"${process.env.TRACKER_DOMAIN}"` : null,
'process.env.USER_SERVICE_ENDPOINT': process.env.USER_SERVICE_ENDPOINT ? `"${process.env.USER_SERVICE_ENDPOINT}"` : null,
__DEV__: DEBUG
};
//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------
const config = {
output: {
publicPath: '/blaze-assets/',
sourcePrefix: ' ',
},
cache: DEBUG,
stats: {
colors: true,
reasons: DEBUG,
hash: VERBOSE,
version: VERBOSE,
timings: true,
chunks: VERBOSE,
chunkModules: VERBOSE,
cached: VERBOSE,
cachedAssets: VERBOSE,
},
plugins: [
new ExtractTextPlugin({
filename: DEBUG ? '[name].css' : '[name].[chunkhash].css',
allChunks: true,
}),
new webpack.LoaderOptionsPlugin({
debug: DEBUG,
})
],
resolve: {
extensions: ['.webpack.js', '.web.js', '.js', '.jsx', '.json'],
modules: [
'./src',
'node_modules',
]
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, '../src'),
],
loader: 'babel-loader',
}, {
test: /\.(scss|css)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
'sass-loader',
]
})
}, {
test: /\.txt$/,
loader: 'raw-loader',
}, {
test: /\.(otf|png|jpg|jpeg|gif|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000',
}, {
test: /\.(eot|ttf|wav|mp3)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
}, {
test: /\.jade$/,
loader: 'jade-loader',
}
],
},
};
//
// Configuration for the client-side bundles
// -----------------------------------------------------------------------------
let clientBundles = {}
Object.keys(bundles).forEach(function (bundle) {
clientBundles[bundle] = [
'bootstrap-loader',
`./src/bundles/${bundle}/index.js`
]
})
merge(
clientBundles,
{
'embedWidget': ['./src/components/Widgets/EmbedWidget/widgetLoader.js']
}
)
const clientConfig = extend(true, {}, config, {
entry: clientBundles,
output: {
path: path.join(__dirname, '../build/public/blaze-assets/'),
filename: DEBUG ? '[name].js' : '[name].[chunkhash].js',
chunkFilename: DEBUG ? '[name].chunk.js' : '[name].[chunkhash:8].chunk.js',
},
node: {
fs: "empty"
},
// Choose a developer tool to enhance debugging
// http://webpack.github.io/docs/configuration.html#devtool
devtool: DEBUG ? 'cheap-module-source-map' : false,
plugins: [
...config.plugins,
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DefinePlugin({
...GLOBALS,
'process.env.BROWSER': true
}),
...(!DEBUG ? [
new webpack.optimize.UglifyJsPlugin({
compress: {
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
screw_ie8: true,
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
warnings: VERBOSE,
},
}),
new webpack.optimize.AggressiveMergingPlugin(),
] : []),
new AssetsPlugin({
path: path.join(__dirname, '../build'),
filename: 'assets.js',
processOutput: x => `module.exports = ${JSON.stringify(x)};`,
}),
],
});
//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------
var srcDirs = {};
fs.readdirSync('src').forEach(function(path) {
srcDirs[path] = true
});
function isExternalFile(context, request, callback) {
var isExternal = request.match(/^[#a-z][a-z\/\.\-0-9]*$/i) && !srcDirs[request.split("/")[0]]
callback(null, Boolean(isExternal));
}
const serverConfig = extend(true, {}, config, {
entry: './src/server.js',
output: {
path: path.join(__dirname, '../build/public/blaze-assets/'),
filename: '../../server.js',
libraryTarget: 'commonjs2',
},
target: 'node',
externals: [
/^\.\/assets$/,
isExternalFile
],
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
},
devtool: DEBUG ? 'cheap-module-source-map' : 'source-map',
plugins: [
...config.plugins,
new webpack.DefinePlugin({
...GLOBALS,
'process.env.BROWSER': false,
'process.env.API_HOST': process.env.API_HOST ? `"${process.env.API_HOST}"` : null
}),
new webpack.NormalModuleReplacementPlugin(/\.(scss|css|eot|ttf|woff|woff2)$/, 'node-noop'),
new webpack.BannerPlugin({
banner: `require('dotenv').config(); require('newrelic'); require('source-map-support').install();`,
raw: true,
entryOnly: false
})
],
});
export default [clientConfig, serverConfig];
here's my start.js file
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import Browsersync from 'browser-sync'
import webpack from 'webpack'
import webpackMiddleware from 'webpack-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import run from './run'
import runServer from './runServer'
import webpackConfig from './webpack.config'
import clean from './clean'
import copy from './copy'
const DEBUG = !process.argv.includes('--release')
/**
* Launches a development web server with "live reload" functionality -
* synchronizing URLs, interactions and code changes across multiple devices.
*/
async function start () {
await run(clean)
await run(copy.bind(undefined, { watch: true }))
await new Promise((resolve) => {
// Patch the client-side bundle configurations
// to enable Hot Module Replacement (HMR) and React Transform
webpackConfig.filter((x) => x.target !== 'node').forEach((config) => {
/* eslint-disable no-param-reassign */
Object.keys(config.entry).forEach((entryKey) => {
if (!Array.isArray(config.entry[entryKey])) {
config.entry[entryKey] = [config.entry[entryKey]]
}
config.entry[entryKey].unshift('webpack-hot-middleware/client')
})
if (config.output.filename) {
config.output.filename = config.output.filename.replace('[chunkhash]', '[hash]')
}
if (config.output.chunkFilename) {
config.output.chunkFilename = config.output.chunkFilename.replace('[chunkhash]', '[hash]')
}
config.plugins.push(new webpack.HotModuleReplacementPlugin())
config.plugins.push(new webpack.NoEmitOnErrorsPlugin())
config
.module
.rules
.filter((x) => x.loader === 'babel-loader')
.forEach((x) => (x.query = {
...x.query,
// Wraps all React components into arbitrary transforms
// https://github.com/gaearon/babel-plugin-react-transform
plugins: [
...(x.query ? x.query.plugins : []),
['react-transform', {
transforms: [
{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module'],
}, {
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react'],
},
],
},
],
],
}))
/* eslint-enable no-param-reassign */
})
const bundler = webpack(webpackConfig)
const wpMiddleware = webpackMiddleware(bundler, {
// IMPORTANT: webpack middleware can't access config,
// so we should provide publicPath by ourselves
publicPath: webpackConfig[0].output.publicPath,
// Pretty colored output
stats: webpackConfig[0].stats,
// For other settings see
// https://webpack.github.io/docs/webpack-dev-middleware
})
const hotMiddlewares = bundler
.compilers
.filter((compiler) => compiler.options.target !== 'node')
.map((compiler) => webpackHotMiddleware(compiler))
let handleServerBundleComplete = () => {
runServer((err, host) => {
if (!err) {
const bs = Browsersync.create()
bs.init({
...(DEBUG ? {} : { notify: false, ui: false }),
proxy: {
target: host,
middleware: [wpMiddleware, ...hotMiddlewares],
},
open: false,
// no need to watch '*.js' here, webpack will take care of it for us,
// including full page reloads if HMR won't work
files: ['build/content/**/*.*'],
}, resolve)
handleServerBundleComplete = runServer
}
})
}
bundler.plugin('done', () => handleServerBundleComplete())
})
}
export default start
I am using react-starter-kit but it is slightly modified version of the original. I have tried degrading css-loader to 0.14.5 to see improvements but no difference. Also, removed sourceMap from UglifyJSPlugin. Any help is appreaciated!

Remove console.logs with Webpack & Uglify

I am trying to remove console.logs with Webpack's Uglify plugin but it seems that Uglify plugin that comes bundled with Webpack doesn't have that option, its not mentioned in the documentation.
I am initializing uglify from webpack like this:
new webpack.optimize.UglifyJsPlugin()
My understanding is that I can use standalone Uglify lib to get all the options, but I don't know which one?
The problem is that drop_console isn't working.
With UglifyJsPlugin we can handle comments, warnings, console logs but it will not be a good idea to remove all these in development mode. First check whether you are running webpack for prod env or dev env, if it is prod env then you can remove all these, like this:
var debug = process.env.NODE_ENV !== "production";
plugins: !debug ? [
new webpack.optimize.UglifyJsPlugin({
// Eliminate comments
comments: false,
// Compression specific options
compress: {
// remove warnings
warnings: false,
// Drop console statements
drop_console: true
},
})
]
: []
Reference: https://github.com/mishoo/UglifyJS2#compressor-options
UPDATE 2019
Need to use terser plugin now for ES6 support in webpack v4
https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
webpack.config.js
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
sourceMap: true, // Must be set to true if using source-maps in production
terserOptions: {
compress: {
drop_console: true,
},
},
}),
],
},
};
Try drop_console:
plugins: [
new Webpack.optimize.UglifyJsPlugin({
compress: {
drop_console: true,
}
}
]
Update: For webpack v4 it has changed a little:
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
...
optimization: {
minimizer: [
new UglifyJSPlugin({
uglifyOptions: {
compress: {
drop_console: true,
}
}
})
]
}
I personally think console logs (especially console.error) are very useful on prod and think it's a good idea to keep them. If you really want to drop specific console functions such as just console.log you should use pure_funcs option e.g. pure_funcs: ['console.log'] and this will drop console.log since pure functions do not produce side effects then Uglify can discard ones not assigned to anything.
optimization: {
minimizer: [
new UglifyJSPlugin({
uglifyOptions: {
compress: {
// Drop only console.logs but leave others
pure_funcs: ['console.log'],
},
mangle: {
// Note: I'm not certain this is needed.
reserved: ['console.log']
}
}
})
]
}
For TerserJS (Uglify is deprecated and does not support new JS features you should NOT use it)
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true
}
}
})
]
}
As discussed you can also use pure_funcs alternatively.
You can use terser-webpack-plugin compress option pure_funcs parameter to selectively drop console functions and keep the ones that you want such as console.error.
I was using "webpack": "^4.39.3" and "terser-webpack-plugin": "^2.3.2".
Steps:
1. npm install terser-webpack-plugin --save-dev
2. modify your webpack.config to set TerserPlugin as a minimizer for optimization option.
const TerserPlugin = require('terser-webpack-plugin');
module.exports = (env) => {
return [{
entry: '...',
mode: 'production',
output: {...},
plugins: [...],
optimization: {
'minimize': true,
minimizer: [new TerserPlugin({
terserOptions: {
compress: {
pure_funcs: [
'console.log',
'console.info',
'console.debug',
'console.warn'
]
}
}
})],
},
module: {...}
}];
};
This is the new syntax for Webpack v4:
optimization: {
minimizer: [
new UglifyJSPlugin({
uglifyOptions: {
compress: {
drop_console: true
},
output: {
comments: false
}
},
}),
],
},
For uglifyjs-webpack-plugin, wrap options inside an uglifyOptions object:
plugins: [
new UglifyJSPlugin({
uglifyOptions: {
compress: {
drop_console: true
}
}
})
]
I have added a comprehensive answer for webpack v4 with debug configuration
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
var debug = process.env.NODE_ENV !== "production";
.....
optimization: {
minimizer: !debug ? [
new UglifyJsPlugin({
// Compression specific options
uglifyOptions: {
// Eliminate comments
comments: false,
compress: {
// remove warnings
warnings: false,
// Drop console statements
drop_console: true
},
}
})
]
: []
}
My scripts in package.json are like so:
"webpackDev": "npm run clean && export NODE_ENV=development && npx webpack",
"webpackProd": "npm run clean && export NODE_ENV=production && npx webpack -p"
this is what I've done to remove alert() and console.log() from my codes.
global_defs => replace alerts with console.log
then drop_console removes all console.logs and now nothing shows up in my browser console
new UglifyJsPlugin({
uglifyOptions: {
compress: {
global_defs: {
"#alert": "console.log",
},
drop_console: true
}
}
}),
plugin versions:
"webpack":3.12.0,
"webpack-cli": "^3.0.3",
"uglifyjs-webpack-plugin": "^1.2.5",
Right now uglifyjs-webpack-plugin v1.2.6 has been released and I used latest documentations for this one, So I suppose there wont be any problem with latest plugin too.
webpack 4.x remove console.log solutions
only remove the console.log but leave other consoles (recommend ✅)
pure_funcs: ['console.log']
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
// webpack.config.js
module.exports = {
// ...
optimization: {
minimizer: [
new UglifyJSPlugin({
uglifyOptions: {
compress: {
pure_funcs: [
'console.log',
// 'console.error',
// 'console.warn',
// ...
],
},
// Make sure symbols under `pure_funcs`,
// are also under `mangle.reserved` to avoid mangling.
mangle: {
reserved: [
'console.log',
// 'console.error',
// 'console.warn',
// ...
],
},
},
}),
],
},
// ...
}
remove all consoles, includes(console.log, console.error, console.warn, ...and so on) (not recommend 🙅🏻‍♂️)
drop_console: true,
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
// webpack.config.js
module.exports = {
// ...
optimization: {
minimizer: [
new UglifyJSPlugin({
uglifyOptions: {
compress: {
drop_console: true,
},
},
}),
],
},
// ...
}
all consoles
Chrome Google, Version 88.0.4324.192 (Official Build) (x86_64)
refs
https://github.com/mishoo/UglifyJS#compress-options
If TerserPlugin's drop_console does not applied, you probably check your build file's extension!
I'm struggling with this with my react project and solved it by adding test regex property for .js (default is .mjs)
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
test: /\.js(\?.*)?$/i, // you should add this property
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log', 'console.info'], // Delete console
},
},
}),
],
},
Use this is better and works
const UglifyEsPlugin = require('uglify-es-webpack-plugin')
module.exports = {
plugins: [
new UglifyEsPlugin({
compress:{
drop_console: true
}
}),
]
}

Resources