Webpack 5 sourcemap loaded by chrome in different "area" - unable to debug - reactjs

I have two react components - I would like to be able to debug the jsx in chrome.
When I load the page I see my component code where I expect (using inline sourcemap)
The sourcemap is loading (it works with a separate source-map file as well as in-line)
But it loads in another section under the "page" menu in chrome.
I see my jsx code as expected here. If I put a breakpoint (say on line 7 in the above picture) it will add the corresponding breakpoint in my minified code. However if I "hit" the breakpoint it will hit in the minified code and not my original jsx (which I thought was possible with sourcemaps in chrome?)
I've used webpack for sourcemaps before - but I don't remember coming across this problem and haven't had any luck searching stackoverflow/google.
Here is my Webpack.Config
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const SourceMapDevToolPlugin = require('webpack/lib/SourceMapDevToolPlugin');
const webpackEntries = {
SavingsGoalAccount: './src/SavingsGoalAccount.jsx',
SavingsGoalsList: './src/SavingsGoalsList.jsx',
};
module.exports = {
mode: 'production',
entry: webpackEntries,
//devtool: "inline-source-map",
devtool: 'source-map',
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[contenthash].js',
library: {
type: 'umd',
name: '[name]',
},
globalObject: 'this',
},
resolve: {
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(css)$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
},
optimization: {
moduleIds: 'deterministic',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: [path.join(__dirname, 'dist/**/*')],
}),
new MiniCssExtractPlugin(),
],
};
It outputs in my dist folder as expected:

Since you're using devTool value as source-map. It will load the original code you wrote as source map. This also happened to me and I changed the devTool value to a different one as per my need.
As per webpack documetation - https://webpack.js.org/configuration/devtool/#devtool
if the quality is original then it'll load the entire code:
quality: original- You will see the original code that you wrote, assuming all loaders support SourceMapping.
If you don't need it. Please go with an option as per your need.

Related

Webpack chunk loading using HTTP instead of HTTPS

I've just converted one of my React components to use lazy loading and although it builds OK, I'm getting a scrip-src CSP error because the chunk is attempting to load over HTTP instead of HTTPS which the site is running. (If I switch CSP off, I get a mixed-content error so it isn't the CSP itself that's causing the problem )
Content Security Policy: The page's settings blocked the loading of a resource at http://passport.local//app/assets/bundle/1.bundle.js ("script-src"). bootstrap:128
I'm using Webpack 4.46.0
Am I missing a setting to force it to use the same protocol as the main application?
Many Thanks.
Neil
My webpack config is below
const webpack = require('webpack');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = (env, argv ) =>
{
const IS_DEVELOPMENT = argv.mode === "development";
const IS_PRODUCTION = argv.mode === "production";
let plugins = [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// all options are optional
filename: path.join('..', 'css', 'app.css'),
//chunkFilename: '[id].css',
ignoreOrder: false, // Enable to remove warnings about conflicting order
}),
new webpack.DefinePlugin({
'__DEV__': JSON.stringify(true),
'__API_HOST__': JSON.stringify('https://passport.local/'),
}),
] ;
return {
devtool: 'source-map',
optimization: {
minimize: IS_PRODUCTION
},
entry: {
main: [
'./_devapp/app.js',
'./_devapp/css/app.scss'
],
login: [
'./_devapp/login.js',
]
},
output: {
path: path.resolve(__dirname, 'assets', 'bundle'),
filename: '[name].bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
alias: {
ui: path.resolve(__dirname, '_devapp/ui/'),
root: path.resolve(__dirname, '_devapp/')
}
},
module: {
rules: [
{
test: /\.(js|jsx|tsx|ts)$/,
exclude: path.resolve(__dirname, 'node_modules'),
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript'
],
plugins: [
["#babel/plugin-proposal-decorators", {"legacy": true}],
'#babel/plugin-syntax-dynamic-import',
['#babel/plugin-proposal-class-properties', {"loose": true}],
["#babel/plugin-proposal-private-property-in-object", { "loose": true }],
["#babel/plugin-proposal-private-methods", {"loose": true}]
]
}
},
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it uses publicPath in webpackOptions.output
publicPath: '../',
},
},
'css-loader',
'postcss-loader',
'sass-loader'
],
},
{
test: /.(png|woff(2)?|eot|ttf|svg|gif)(\?[a-z0-9=\.]+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '../css/[hash].[ext]'
}
}
]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
}
]
},
externals: {
myApp: 'myApp',
},
plugins: plugins,
};
}
I managed to resolve this. It was caused by a webpack_public_path definition buried in my code. I'd inherited this line in the react site template I used many years ago and never knew what it did... until now:
__webpack_public_path__ = `${window.STATIC_URL}/app/assets/bundle/`;
${window.STATIC_URL} is (at least on my platform) an http:// constant and overrides the https:// that the main site is running on.
Commenting out this line resolved the problem :-)

ReactJS / Styled-Components: CSS Compatibilty Issues Across Browers

Currently having CSS compatibility issues across browsers with a site built using react and linaria. Linaria is essentially a styled-components library that has its CSS-in-JS extracted into a CSS file during the build step.
The solution I believe is to use PostCSS. However as I am new to this tool, I am trying to work out how to integrate it properly into my webpack config. Especially, to ensure it runs after the linaria styles have been extracted.
The two questions are:
Is my postcss.config.js correct, as I'm not sure if I should be using both autoprefixer and postcss-preset-env. Also, is my .browserslistrc correct to target the most recent versions of: Safari, Edge, Chrome and Firefox.
Is my webpack.config.ts correct to ensure postcss is run on my extracted CSS from linaria styled-components.
See the relevant config files below.
Thanks.
webpack.config.ts
const configuration = (env: Record<string, any>, argv: Record<string, any>): Configuration => ({
entry: getEntries,
output: {
path: path.resolve(__dirname, "assets"),
filename: "[name].js",
},
plugins: [
new MiniCssExtractPlugin({
filename: "main.css",
})
],
optimization: {
splitChunks: {
cacheGroups: {
styles: {
name: "styles",
type: "css/mini-extract",
chunks: "all",
enforce: true,
},
},
},
},
module: {
rules: [
{
test: /\.tsx?$/i,
exclude: /node_modules/,
use: [
"babel-loader",
"#linaria/webpack-loader",
],
},
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
importLoaders: 1,
}
},
"postcss-loader",
],
},
],
},
resolve: {
extensions: [".tsx", ".ts", "..."],
},
});
export default configuration;
postcss.config.js
module.exports = {
plugins: [
require("autoprefixer"),
require("postcss-preset-env"),
]
};
.browerslistrc
last 4 versions

Webpack bundle throwing content length mismatch error

I'm working on a React project that gets served by a Go application.
I've been trying to integrate a component library, first with Ant Design, and now with Material UI.
In both instances, as soon as I add a simple component (in this case a Button), my webpack bundle throws net::ERR_CONTENT_LENGTH_MISMATCH in Chrome.
Before adding a component library, my outputted bundle is around 1mb, when adding Material it grows to about 5.5mb, with Ant it was about 11mb.
The strange behavior is that this only happens when I bundle the resources in the development mode configuration with Webpack. If I build for production, everything is fine, although I do get the warning about the bundle size exceeding the recommended limit.
My webpack looks like this:
const path = require("path");
const webpack = require("webpack");
const dotenv = require("dotenv-webpack");
const miniCSS = require("mini-css-extract-plugin");
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
entry: path.resolve(__dirname, "src/index.tsx"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/anx.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js"],
alias: {
components: path.resolve(__dirname, "src/components"),
containers: path.resolve(__dirname, "src/containers"),
src: path.resolve(__dirname, "src"),
},
},
plugins: [
new miniCSS({
filename: "css/anx.css",
}),
],
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader",
},
],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: miniCSS.loader,
options: {
publicPath: "/dist/css",
},
},
"css-loader",
],
},
{
test: /\.s[ac]ss$/,
use: [
{
loader: miniCSS.loader,
options: {
publicPath: "/dist/css",
},
},
"css-loader",
"sass-loader",
],
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader",
},
],
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
react: "React",
"react-dom": "ReactDOM",
},
};
if (process.env.NODE_ENV === "production") {
module.exports.devtool = "source-map";
module.exports.mode = "production";
module.exports.optimization = { minimize: true };
module.exports.plugins = (module.exports.plugins || []).concat([
new CopyPlugin([
{
from: "node_modules/react/umd/react.production.min.js",
to: "js/react.js",
},
{
from: "node_modules/react-dom/umd/react-dom.production.min.js",
to: "js/react-dom.js",
},
]),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: '"production"',
},
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
}),
]);
} else {
module.exports.devtool = "eval-source-map";
module.exports.mode = "development";
module.exports.plugins = (module.exports.plugins || []).concat([
new CopyPlugin([
{
from: "node_modules/react/umd/react.development.js",
to: "js/react.js",
},
{
from: "node_modules/react-dom/umd/react-dom.development.js",
to: "js/react-dom.js",
},
]),
new dotenv({ path: "secrets/.env.dev" }),
]);
}
I suspect that, in development mode, Webpack includes the source maps and the bundle balloons in size, and this somehow results in the content mismatch error. However, I'm not totally sure. Any help would be appreciated
edit: I found a working solution for this by replacing eval-source-map with source-map in the development environments devtool. I'm not totally sure why this works; my suspicion is that it has something to do with my project running on WSL and the bundle sizes that are produced.

why material-ui takes too much space?

I am using webpack to bundle my react project. My project depends on material-ui for below component:
material-ui/Dialog
material-ui/styles/getMuiTheme
material-ui/styles/MuiThemeProvider
material-ui/FlatButton
material-ui/TextField
webpack-bundle-size-analyzer reports material-ui takes 1.07MB size. Below is my webpack config file:
const webpack = require('webpack');
const path = require('path');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const WebpackShellPlugin = require('webpack-shell-plugin');
var CompressionPlugin = require("compression-webpack-plugin");
const PATHS = {
react: path.join(__dirname, 'node_modules', 'react', 'dist', 'react.min.js'),
app: path.join(__dirname, 'src'),
build: path.join(__dirname, './dist')
};
module.exports = {
entry: {
app: './app/index.jsx',
android: './app/utils/platform_android.js',
ios: './app/utils/platform_ios.js',
web: './app/utils/platform_web.js',
vendor: [
'axios',
'react',
'react-dom',
'react-redux',
'react-router',
'react-router-redux',
'redux',
'redux-thunk',
'react-alert',
'sha1',
'moment',
'nuka-carousel',
'react-cookie',
'material-ui',
'react-spinkit',
'react-tap-event-plugin',
'react-tappable',
'history',
],
},
output: {
path: PATHS.build,
filename: '[name].bundle.js',
},
watch: false,
devtool: 'source-map',
relativeUrls: true,
resolve: {
extensions: ['', '.js', '.jsx', '.css', '.less'],
modulesDirectories: ['node_modules'],
alias: {
normalize_css: __dirname + '/node_modules/normalize.css/normalize.css',
}
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
},
// {
// test: /\.js$/,
// exclude: /node_modules/,
// loader: 'jshint-loader'
// }
],
loaders: [
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader?presets=es2015',
},
{
test: /\.less$/,
loader: "style!css!less",
},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /\.png$/, loader: "url-loader?limit=100000"},
// {test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=/public/icons/[path]/[name].[ext]"},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader?presets=es2015']
},
{
test: /\.svg$/,
loader: 'svg-sprite',
include: /public\/icons/
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
minimize: true
}),
new NpmInstallPlugin({
save: true // --save
}),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new WebpackShellPlugin({
onBuildStart: ['echo "Webpack Start"'],
onBuildEnd: [
'cp ./dist/*.js ../assets/dist/;rm -fr dist/web;' +
'mkdir -p dist/web/dist;cp ./dist/*.js ./dist/web/dist/;cp ./index.html ./dist/web/;cp -r public dist/web/',
]
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */["vendor"], /* filename= */"[name].bundle.js", Infinity),
],
devServer: {
colors: true,
contentBase: __dirname,
historyApiFallback: true,
hot: true,
inline: true,
port: 9093,
progress: true,
stats: {
cached: false
}
}
}
I already tried to use CompressionPlugin, UglifyJsPlugin to optimize my bundle files but it still takes more than 1MB. How can I reduce its size? I don't want to use gzip since my app is running on webview on mobile device and some of them doesn't support gzip encoding.
Finally I figured out what the problem. In my webpack config file, I separate all vendor js into a different js bundle file. And I listed 'material-ui' there. When package my app, the whole 'material-ui' library will be packaged into vendor.js. I have to remove the material-ui from vendor list, in this way only the components required by my source code will be packaged.
There are a couple of things you could do to reduce the size:
Make sure you are only requiring in the components you need from material-ui and not the whole library
Try using Minifyify
See more suggestions in this GitHub Issue.
I would go for Option 2 listed in their documentation here: Minimizing Bundle Size. They suggest this provides a much better experience for both developers and users, I think with much faster loading times for both.
Setup your Babel configuration with babel-plugin-import or babel-plugin-transform-imports. These configurations make sure only the files that you use from Material-UI are included in your builds.
Convert all you Material-UI import statements as such:
-import Button from '#material-ui/core/Button';
-import TextField from '#material-ui/core/TextField';
+import { Button, TextField } from '#material-ui/core';

React-fetch requires react-addons, but there is no react/addons folder

Edit: The author has patched it.
I'm beginning to use react-fetch (well, trying to), and when trying to run webpack, I got this error :
ERROR in ./~/react-fetch/build/react-fetch.js
Module not found: Error: Cannot resolve 'file' or 'directory' E:\Users\Adrien\Documents\GitHub\brigad-admin-frontend/node_modules/react/addons in E:\Users\Adrien\Documents\GitHub\brigad-admin-frontend\node_modules\react-fetch\build
# ./~/react-fetch/build/react-fetch.js 17:19-42
But, as the error says, I have no react/addons folder (I'm using React 15.0.1).
Does anybody have had this issue before?
Thanks in advance.
PS: Here's my webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const nodeDir = `${__dirname}/node_modules`;
const config = {
resolve: {
alias: {
react: `${nodeDir}/react`,
'react-dom': `${nodeDir}/react-dom`,
'react-router': `${nodeDir}/react-router`,
'react-fetch': `${nodeDir}/react-fetch`,
'react-bootstrap': `${nodeDir}/react-bootstrap`,
velocity: `${nodeDir}/velocity-animate`,
moment: `${nodeDir}/moment`,
slimscroll: `${nodeDir}/slimscroll`,
},
},
entry: {
routes: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./public/src/routes/js/main',
],
vendors: [
'react', 'react-dom', 'react-router', 'react-fetch', 'react-bootstrap',
'velocity', 'moment', 'slimscroll',
],
// chartVendors: ['raphael', 'morris'],
},
output: {
path: path.join(__dirname, 'public/dist'),
// publicPath: path.join(__dirname, 'public/dist/'),
filename: 'bundles/[name].bundle.js',
chunkFilename: 'chunks/[name].chunk.js',
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'public'),
loader: 'react-hot',
},
{
test: /\.js$/,
include: path.resolve(__dirname, 'public'),
loader: 'babel',
},
{
test: /\.css$/,
include: path.join(__dirname, 'public'),
loader: 'style!css-loader?modules&importLoaders=1' +
'&localIdentName=[name]__[local]___[hash:base64:5]',
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin('vendors', './bundles/vendors.js', Infinity),
],
};
module.exports = config;
React API has changed. import React from 'react/addons' isn't valid in the current version. I can see the author uses React.addons.cloneWithProps from there.
The documentation suggests using React.cloneElement instead.
You could tweak the code accordingly and submit a PR to get this fixed.

Resources