Disable file chunking with CRACO - reactjs

I am trying to figure out how to use CRACO (https://github.com/gsoft-inc/craco) to disable file chunking in create react app.
I have created the following craco.config.js:
// craco.config.js
module.exports = {
output: {
fileName: 'static/js/bundle.js',
},
}
But it doesn't have any effect. What should the config look like to disable file chunking in CRA with CRACO?

EDIT: To disable chunking completely I believe this might do it.
Source: https://github.com/facebook/create-react-app/issues/5306#issuecomment-650737697
// craco.config.js
module.exports = {
webpack: {
configure: {
optimization: {
runtimeChunk: false,
splitChunks: {
chunks(chunk) {
return false
},
},
},
},
},
}
ORIGNIAL:
Maybe this could help?
module.exports = {
webpack: {
configure: {
output: {
filename: 'static/js/bundle.js',
},
optimization: {
runtimeChunk: false,
splitChunks: {
chunks: 'all',
cacheGroups: {
default: false,
vendors: false,
// vendor chunk
},
},
},
},
},
plugins: [
{
plugin: require('craco-plugin-scoped-css'),
},
],
}

Related

You may need an appropriate loader to handle this file type with scss even through added loader

After I add the scss file import:
import '#/style/view-style/index.scss'
the webpack 5 compiler shows error:
Why you should do it regularly:
https://github.com/browserslist/browserslist#browsers-data-updating
Bundle with webpack 5...
Starting the development server...
✖ Webpack
Compiled with some errors in 1.93s
ERROR Failed to compile with 1 errors 11:57:39 PM
error in ./src/style/view-style/index.scss
Module parse failed: Unexpected token (1:0)
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
> .index {
| padding: 1.6rem 0;
| .index-header {
[change] config/webpack.base.config.js
[change] config/webpack.base.config.js
[change] config/webpack.base.config.js
[change] config/webpack.base.config.js
I have checked the webpack config file and already added the loader:
{
test : /.s?css$/,
use: [MiniCssExtractPlugin.loader,'css-loader', 'sass-loader']
}
why still shows error like this? what should I do to avoid this problem? This is the full webpack config:
const path = require('path');
const CopyPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const paths = require('./paths');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = {
entry : './src/index.js',
devServer: {
port: 3000,
compress: true,
open: true,
hot: true,
},
resolve: {
extensions: ['.tsx', '.ts', '.js','.jsx'],
alias: {
'#': path.resolve(__dirname, '../src'),
},
},
output : {
path : path.resolve(__dirname, '../build') ,
filename : 'js/bundle.js'
},
module : {
rules : [
{
test: /\.ts$/,
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/]
},
exclude: /node_modules|\.d\.ts$/
},
{
test: /\.d\.ts$/,
loader: 'ignore-loader'
},
{
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
},
},
{
test : /.s?css$/,
use: [MiniCssExtractPlugin.loader,'css-loader', 'sass-loader']
},
// https://stackoverflow.com/questions/69427025/programmatic-webpack-jest-esm-cant-resolve-module-without-js-file-exten
{
test: /\.m?js/,
type: "javascript/auto",
},
{
test: /\.m?js/,
resolve: {
fullySpecified: false,
},
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
options: {
name: '/public/icons/[name].[ext]'
}
}
]
},
optimization:{
minimize: true,
minimizer: [
`...`,
new CssMinimizerPlugin(),
],
},
plugins : [
new MiniCssExtractPlugin({
filename: 'static/css/[name].css',
chunkFilename: 'static/css/[name].chunk.css',
}),
new CopyPlugin({
patterns: [
{ from: "public/index.html", to: "index.html" },
{ from: "public/favicon.png", to: "public/favicon.png" },
{ from: "public/manifest.json", to: "public/manifest.json" },
],
}),
]
};

firebase with react and custom webpack throws export loader error

i'm facing an issue with react with custom webpack config while I try to implement firebase
react version: 17+
webpack version: 5+
firebase: 9+
so when i try to import any function from firebase/messaging (also tried other packages from firebase like analytics, same issue happens) it throws an error about exports-loader module that is not installed.
then after installation it throws this error then:
ERROR in ./node_modules/whatwg-fetch/fetch.js (./node_modules/exports-loader/dist/cjs.js?self.fetch!./node_modules/whatwg-fetch/fetch.js)
Module build failed (from ./node_modules/exports-loader/dist/cjs.js):
ValidationError: Invalid options object. Exports Loader has been initialized using an options object that does not match the API schema.
options misses the property 'exports'. Should be:
non-empty string | non-empty string | object { name, syntax?, alias? } | [non-empty string | object { name, syntax?, alias? }, ...] (should not
have fewer than 1 item)
here is my webpack config, is there anything that I'm missing from webpack config or is this issue caused by webpack at all?
module.exports = {
devtool: 'eval',
entry: ['app/app.js'],
loader: { target: 'web' },
mode: 'development',
module: {
strictExportPresence: true,
rules: [
{
test: /\.svg/,
use: {
loader: 'svg-url-loader',
options: {
iesafe: true,
},
},
},
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
loader: 'babel-loader',
include: [PATHS.APP_DIR],
exclude: [/node_modules/],
options: {
...babelConfig,
},
},
{
test: /\.(eot|otf|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'fonts',
},
},
],
},
{
test: /\.(gif|png|jpe?g)$/i,
use: [
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65,
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.9],
speed: 4,
},
gifsicle: {
interlaced: false,
},
// the webp option will enable WEBP
webp: {
quality: 75,
},
},
},
{
loader: 'file-loader',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'images',
},
},
],
},
{
test: /\.(s*)css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 1,
},
},
],
},
],
},
node: { global: false, __dirname: false, __filename: false },
output: {
path: 'build/',
publicPath: '/',
filename: '[name].js',
chunkFilename: '[name].chunk.js',
},
plugins: [
new WebpackBar({
name: 'CSR',
color: '#FFEB3B',
}),
new webpack.ProvidePlugin({
// make fetch available
fetch: 'exports-loader?self.fetch!whatwg-fetch',
}),
new webpack.DefinePlugin({
'process.env': webpackEnv(),
}),
new LoadablePlugin({
filename: 'loadable-stats.json',
writeToDisk: true,
}),
new CopyPlugin({
patterns: [
{
from: path.join('resources', 'public'),
to: 'build',
},
],
}),
new HtmlWebPackPlugin({
template: `/index.ejs`,
title: 'MY APP',
}),
new webpack.HotModuleReplacementPlugin({
multiStep: false,
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/, // exclude node_modules
failOnError: false, // show a warning when there is a circular dependency
}),
],
resolve: {
modules: ['node_modules'],
alias: {
// my aliases
},
},
stats: { preset: 'minimal', moduleTrace: true, errorDetails: true },
target: 'web',
};
the issue was caused by whatwg-fetch
fetch: 'exports-loader?self.fetch!whatwg-fetch',
by removing this line since it wasn't necessary, the problem has been solved

Webpack 5 - "Unexpected token: punc (.)" after import axios

I am getting a strange issue on bundling webpack for production environment.
Unexpected token: punc (.)
This happens only when a React component imports axios
import React from "react";
import axios from "axios"; // <---------------
class SimpleComponent extends React.Component {
render() {
return (
<section className="bg-white py-16">
Simple
</section>
)
}
}
export default SimpleComponent
This results in the following error:
$ npm run build
ERROR in static/main.b394a534fa5736fe90cc.js from Terser
Unexpected token: punc (.) [static/main.b394a534fa5736fe90cc.js:18978,6]
at js_error (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:546:11)
at croak (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1264:9)
at token_error (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1272:9)
at unexpected (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1278:9)
at statement (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1397:17)
at _embed_tokens_wrapper (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1322:26)
at block_ (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:2155:20)
at statement (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1386:29)
at _embed_tokens_wrapper (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1322:26)
at if_ (/home/franciscocarvalho/code/oss/axios-issue-example-with-webpack5/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:2141:21)
To Reproduce
Please fork the following axios-issue-example-with-webpack5 repository
Perform npm install
Run npm run build
Expected behavior
None error after bundle
Environment
Axios Version [0.21.1]
Node.js Version [v12.20.1]
Additional Library Versions [React 17.0.1, Webpack 5.15.0]
webpack.config
const path = require("path")
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const {CleanWebpackPlugin} = require("clean-webpack-plugin")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const Dotenv = require("dotenv-webpack")
const ROOT_DIR = path.resolve(__dirname, "..")
module.exports = {
mode: "production",
entry: [
path.resolve(ROOT_DIR, "./src/index.js"),
path.resolve(ROOT_DIR, "./src/styles/styles.scss")
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
"babel-loader",
{
loader: "eslint-loader",
options: {
configFile: path.resolve(ROOT_DIR, ".eslintrc")
}
}
]
},
{
test: /\.(jpe?g|png|gif|ico|svg|woff|woff2|webp)$/i,
use: [
{
loader: "file-loader",
options: {
name: "static/[name].[ext]"
}
}
]
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
importLoaders: true
}
},
'postcss-loader',
{
loader: "sass-loader",
options: {
sassOptions: {
includePaths: [
path.resolve(ROOT_DIR, "node_modules"),
path.resolve(ROOT_DIR, "src/styles/")
]
}
}
}
],
}
]
},
resolve: {
extensions: ["*", ".js", ".jsx", ".scss"],
fallback: {
assert: false,
http: false,
https: false,
zlib: false,
tty: false,
util: false,
fs: false,
net: false,
stream: false
}
},
plugins: [
new Dotenv({
path: path.resolve(__dirname, "..", "./.env")
}),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Advanced React with Webpack Setup",
template: path.resolve(__dirname, "..", "./src/index.ejs")
}),
new MiniCssExtractPlugin({
filename: "static/[name]-[contenthash].css",
}),
new PurgeCSSPlugin({
paths: glob.sync(`${ROOT_DIR}/src/**/*`, {nodir: true}),
}),
],
stats: {
modules: true,
hash: true,
assetsSort: "!size",
children: true
},
output: {
path: path.resolve(__dirname, "..", "dist"),
chunkFilename: 'static/[name].[hash].js',
filename: "static/[name].[hash].js",
chunkLoading: false,
wasmLoading: false
},
optimization: {
minimize: true,
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
new CssMinimizerPlugin(),
/*new UglifyJsPlugin({
test: /\.js(\?.*)?$/i,
parallel: true,
})*/
new TerserPlugin({
terserOptions: {
ecma: 6,
compress: {
warnings: true
},
output: {
comments: false,
beautify: false
}
}
})
],
},
}
Problem
Like I said the problem is from debug which has been included by webpack in your built file (the node code part). That code looks like:
function save(namespaces) {
if (null == namespaces) {
delete {}.DEBUG;
} else {
{}.DEBUG = namespaces; // that is the invalid statement that `terser` complains about
}
}
// Plus, the main file `index.js` of `debug`:
if (typeof process !== 'undefined' && process.type === 'renderer') {
module.exports = require('./browser.js');
} else {
// Above code is from here
module.exports = require('./node.js');
}
Solution
Above code of debug for node has been added since you haven't yet told webpack you build for web app so then it won't include that code.
So as long as you set target as web in your configuration, then it would work:
webpack.common.js
module.exports = {
target: 'web',
// ...
}
One more thing I found that your css typeface-roboto you imported requires you set publicPath as output:
webpack.prod.js
module.exports = {
// ...
output: {
// ...
publicPath: '/',
},
}

Integrating React Js with AEM CMS (Adobe Experience Manager CMS)

I am trying to integrate react js application into existing AEM CMS application and below is the way how i am trying to put the values in setting for AEM CMS
And below is the configuration generated by CMS in div :
<div data-t-name="CustomComponent"
data-css="xxx/styles/main.css"
data-js="xxx/main.js">
<div
id="xxxx"
data-application-name="xxx" data-config='
{
"ID": "bb70cfde887ba7157a2dec3ff1d539ea40d817d97ad270278ba982008f918f96",
"EMBEDDED": true,
"LOCALE": "en",
"organizationId": "xxx",
"eventId": "xxx"
}'>
</div>
</div>
Issue is when i try to put css and js referance as entry point into above setting below is error i have received , any one please guide or clues to sort this issue
Please find the webpack config below :
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const project = require('../project.config');
const inProject = path.resolve.bind(path, project.basePath);
const inProjectSrc = (file) => inProject(project.srcDir, file);
const __DEV__ = project.env === 'development';
const __TEST__ = project.env === 'test';
const __PROD__ = project.env === 'production';
const config = {
entry: {
normalize: [
inProjectSrc('normalize'),
],
main: [
inProjectSrc(project.main),
],
},
devtool: project.sourcemaps ? 'source-map' : false,
output: {
path: inProject(project.outDir),
filename: '[name].js',
publicPath: project.publicPath,
},
resolve: {
modules: [
inProject(project.srcDir),
'node_modules',
],
extensions: ['*', '.js', '.jsx', '.json'],
},
externals: project.externals,
module: {
rules: [],
},
plugins: [
new webpack.DefinePlugin(Object.assign({
'process.env': { NODE_ENV: JSON.stringify(project.env) },
__DEV__,
__TEST__,
__PROD__,
}, project.globals)),
],
};
// JavaScript
// ------------------------------------
config.module.rules.push({
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
query: {
cacheDirectory: true,
plugins: [
'babel-plugin-transform-decorators-legacy',
'babel-plugin-transform-class-properties',
'babel-plugin-syntax-dynamic-import',
[
'babel-plugin-transform-runtime',
{
helpers: true,
polyfill: false, // we polyfill needed features in src/normalize.js
regenerator: true,
},
],
[
'babel-plugin-transform-object-rest-spread',
{
useBuiltIns: true, // we polyfill Object.assign in src/normalize.js
},
],
],
presets: [
'babel-preset-react',
['babel-preset-env', {
modules: false,
targets: {
ie9: true,
},
uglify: true,
}],
],
},
}],
});
// Styles
// ------------------------------------
const extractStyles = new ExtractTextPlugin({
filename: 'styles/[name].css',
allChunks: true,
disable: __DEV__,
});
config.module.rules.push({
test: /\.(sass|scss)$/,
loader: extractStyles.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: project.sourcemaps,
minimize: {
autoprefixer: {
add: true,
remove: true,
browsers: ['last 2 versions'],
},
discardComments: {
removeAll: true,
},
discardUnused: false,
mergeIdents: false,
reduceIdents: false,
safe: true,
sourcemap: project.sourcemaps,
},
},
},
{
loader: 'sass-loader',
options: {
sourceMap: project.sourcemaps,
includePaths: [
inProjectSrc('styles'),
],
},
},
],
}),
});
config.plugins.push(extractStyles);
// Images
// ------------------------------------
config.module.rules.push({
test: /\.(png|jpg|gif|jpeg|JPG|)$/,
loader: 'url-loader',
options: {
limit: 8192,
},
})
// Fonts
// ------------------------------------
;[
['woff', 'application/font-woff'],
['woff2', 'application/font-woff2'],
['otf', 'font/opentype'],
['ttf', 'application/octet-stream'],
['eot', 'application/vnd.ms-fontobject'],
['svg', 'image/svg+xml'],
].forEach((font) => {
const extension = font[0];
const mimetype = font[1];
config.module.rules.push({
test: new RegExp(`\\.${extension}$`),
loader: 'url-loader',
options: {
name: 'fonts/[name].[ext]',
limit: 10000,
mimetype,
},
});
});
// HTML Template
// ------------------------------------
config.plugins.push(new HtmlWebpackPlugin({
template: inProjectSrc('index.html'),
inject: true,
minify: {
collapseWhitespace: true,
},
}));
// Development Tools
// ------------------------------------
if (__DEV__) {
config.entry.main.push(
`webpack-hot-middleware/client.js?path=${config.output.publicPath}__webpack_hmr`
);
config.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin()
);
}
// Bundle Splitting
// ------------------------------------
if (!__TEST__) {
const bundles = ['normalize', 'manifest'];
if (project.vendors && project.vendors.length) {
bundles.unshift('vendor');
config.entry.vendor = project.vendors;
}
config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ names: bundles }));
}
// Production Optimizations
// ------------------------------------
if (__PROD__) {
config.plugins.push(
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: !!config.devtool,
comments: false,
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
},
})
);
}
module.exports = config;

Issue with Webpack 4.1.1 and UglifyJS2 - Production mode mangles code which throws uncaught error

I've upgraded a project to Webpack 4.1.1 and encountered a bug with UglifyJS that I cant seem to get around.
Minimum reproducible repo here: https://github.com/jamesopti/uglifyjs-webpack-issue
Although I think this is a bug, I'd like to try and configure UglifyJS to work around it. No luck so far despite the options shown below.
uglifyOptions: {
mangle: false,
keep_classnames: true,
keep_fnames: true,
},
Any ideas?
Main.js code:
import React from 'react';
import { render } from 'react-dom';
import ReactCodeMirror from 'react-codemirror';
// Enables syntax highlighting for javascript
require('codemirror/mode/javascript/javascript');
// Enables linting for javascript
require('codemirror/addon/lint/lint');
require('codemirror/addon/lint/javascript-lint');
window.JSHINT = require('jshint').JSHINT;
const defaultOptions = {
lint: true,
};
render(
<ReactCodeMirror
options={defaultOptions}
value={'some\ncode'}
/>, document.querySelector('#root')
);
Webpack config:
entry: './src/main.js',
mode: 'development',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{ test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ] },
{ test: [/\/src\/(?:.*)\.js$/], use: { loader: 'babel-loader' } },
]
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
mangle: false,
keep_classnames: true,
keep_fnames: true,
},
}),
]
}
The root cause of this is a bug in UglifyJS (reported here).
Minimal reproducible code:
(function(mod) {
mod();
})(function() {
function getMaxSeverity(ax, bx) {
if (ax === "error") {
return ax;
} else {
return bx;
}
}
function main() {
var arr = ['hey'];
for (var i = 0; i < arr.length; i++) {
console.log(getMaxSeverity('one', 'two'));
}
}
main();
});
The workaround is the compress inline option
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
compress: {
inline: 1,
}
}
})
]
}

Resources