i18next + React + Webpack - getFixedT is not a function - reactjs

I'm having some trouble with React, i18next and Webpack. I've tried many solutions, but none of them worked. When I try to build my application, it builds successfully. But, when I try to open it, the console shows an error. My webpack.config and the error stacktrace are below.
webpack.prod.config.js
const webpack = require('webpack');
const path = require('path');
const htmlWebpackPlugin = require("html-webpack-plugin")
const miniCSSExtractPlugin = require("mini-css-extract-plugin")
const terserPlugin = require("terser-webpack-plugin")
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin")
const cleanWebpackPlugin = require("clean-webpack-plugin")
const i18nPlugin = require("i18n-webpack-plugin")
const options = require("../src/controllers/i18n").options
const locales = require("../src/controllers/i18n/locales")
options.backend.loadPath = "." + options.backend.loadPath
const config = {
mode: "production",
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: "./",
filename: 'bundle.js'
},
resolve: {
extensions: [" ", ".js", ".jsx"],
alias: {
"#components": path.resolve(__dirname, "../src/components"),
"#views": path.resolve(__dirname, "../src/views")
}
},
optimization: {
minimizer: [
new terserPlugin({
cache: true,
parallel: true,
include: /\.(js|jsx)$/
}),
new OptimizeCSSAssetsPlugin({})
]
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [{
loader: "babel-loader"
}, {
loader: "i18next-loader"
}]
},
{
test: /\.css$/,
use: [
miniCSSExtractPlugin.loader,
{
loader: "css-loader",
}
]
}, {
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader?name=images/[hash].[ext]',
options: {
name: "assets/images/[hash].[ext]"
}
}]
}, {
test: /\.(ttf|woff(2)|eof|svg)$/,
use: [{
loader: "file-loader",
options: {
name: "assets/fonts/[hash].[ext]",
}
}]
}
],
},
plugins: [
new htmlWebpackPlugin({
template: path.join(__dirname, "..", "public", "index.html")
}),
new miniCSSExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new cleanWebpackPlugin("../dist/*", {
root: __dirname + "../",
allowExternal: true
}),
new i18nPlugin(locales,{
functionName: "t",
nested: true
},true)
]
};
module.exports = config;
The npm run build runs normally, no errors about i18next. Then, when I open the application, I got this error:
bundle.js:33 TypeError: r.getFixedT is not a function
at L (bundle.js:12)
at bundle.js:12
at Xo (bundle.js:33)
at Ia (bundle.js:33)
at qi (bundle.js:33)
at $i (bundle.js:33)
at jl (bundle.js:33)
at Cl (bundle.js:33)
at Pl (bundle.js:33)
at Ji (bundle.js:33)
Hope somebody can helps me.

I've found what was the problem. The i18next documentation says that I should run the init inside the webpack.config.js.
The Problem
My initial problem was loading the locales. The i18n couldn't find the files after the build, because the webpack doesn't recognize the i18n-xhr-backend requiring the .json files. After the build, there was no translation files. Then, I've tried to let webpack deal with the i18n, and I got another problem, on next paragraph.
The React needs the i18n instance to be add to the i18nextProvider. But, the way that I was doing it, there was no i18n instance to refence inside React. Then, it coudn't find the translation function or anything else. I've also found the i18nWebpackPlugin, but it also didn't solved my problem, because it don't give access to the i18n instance inside react. At the end, I had two unsolved problems.
The Solution
My solution was quite simple. I've created a new i18n config to the development env and let the webpack deal with the .json, copying it to a new folder after build. I'll let my webpack and i18n config files below. The steps were:
Bring i18n.init() back to i18n/index.js
Create different options for each environment
Configure webpack to copy translation files
Import the i18n instance on App.js again
Now, everything works like a charm.
OBS: To webpack recognize the .json files, you need to import it somewhere. I did inside the resources.js file.
webpack.prod.config.js
const webpack = require("webpack");
const path = require("path");
const htmlWebpackPlugin = require("html-webpack-plugin");
const miniCSSExtractPlugin = require("mini-css-extract-plugin");
const terserPlugin = require("terser-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const cleanWebpackPlugin = require("clean-webpack-plugin");
const config = {
mode: "production",
output: {
path: path.resolve(__dirname, "../dist"),
publicPath: "./",
filename: "bundle.js"
},
resolve: {
extensions: [" ", ".js", ".jsx"],
alias: {
"#components": path.resolve(__dirname, "../src/components"),
"#views": path.resolve(__dirname, "../src/views"),
"#static": path.resolve(__dirname, "../src/static")
}
},
optimization: {
minimizer: [
new terserPlugin({
cache: true,
parallel: true,
include: /\.(js|jsx)$/
}),
new OptimizeCSSAssetsPlugin({})
]
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader"
}
]
},
{
test: /\.css$/,
use: [
miniCSSExtractPlugin.loader,
{
loader: "css-loader"
}
]
},
{
test: /\.(png|jpg|gif|ico)$/,
use: [
{
loader: "file-loader?name=images/[hash].[ext]",
options: {
name: "assets/images/[hash].[ext]"
}
}
]
},
{
test: /\.(ttf|woff2?|eo(f|t)|svg)$/,
use: [
{
loader: "file-loader",
options: {
name: "assets/fonts/[hash].[ext]"
}
}
]
},
{
test: /\.(json)$/,
type: "javascript/auto",
use: [
{
loader: "file-loader",
options: {
name: "[folder]/[name].[ext]",
outputPath: "assets/locales/"
}
}
]
}
]
},
plugins: [
new htmlWebpackPlugin({
template: path.join(__dirname, "..", "public", "index.html")
}),
new miniCSSExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new cleanWebpackPlugin("../dist/*", {
root: __dirname + "../",
allowExternal: true
})
]
};
module.exports = config;
i18n/index.js
const i18n = require("i18next");
const initReactI18next = require("react-i18next").initReactI18next;
const langDetector = require("i18next-browser-languagedetector");
const backend = require("i18next-xhr-backend");
const moment = require("moment");
const resources = require("../../static/locales");
/*
Other codes...
*/
i18n.use(langDetector).use(initReactI18next);
var options;
switch (process.env.NODE_ENV) {
case "test":
options = {
whitelist: ["en", "pt"],
fallbackLng: "en",
resources,
ns: "translation",
defaultNS: "translation",
interpolation: {
format: function(value, format, lng) {
if (value instanceof Date) return moment(value).format(format);
return value.toString();
}
}
};
break;
case "production":
i18n.use(backend);
options = {
whitelist: ["en-US", "pt-BR"],
fallbackLng: {
pt: ["pt-BR"],
en: ["en-US"],
default: ["en"]
},
ns: ["button", "common", "lng", "info"],
defaultNS: "common",
backend: {
loadPath: "./assets/locales/{{lng}}/{{ns}}.json"
},
detection: {
order: ["querystring", "cookie", "navigator", "localStorage"]
},
lookupQuerystring: "lng",
caches: ["localStorage", "cookie"],
react: {
wait: true
},
interpolation: {
format: function(value, format, lng) {
if (format === "uppercase") return value.toUpperCase();
if (value instanceof Date) return moment(value).format(format);
return value;
}
}
};
break;
case "development":
i18n.use(backend);
options = {
whitelist: ["en-US", "pt-BR"],
fallbackLng: {
pt: ["pt-BR"],
en: ["en-US"],
default: ["en"]
},
ns: ["button", "common", "lng", "info"],
defaultNS: "common",
backend: {
loadPath: "./src/static/locales/{{lng}}/{{ns}}.json"
},
detection: {
order: ["querystring", "cookie", "navigator", "localStorage"]
},
lookupQuerystring: "lng",
caches: ["localStorage", "cookie"],
react: {
wait: true
},
interpolation: {
format: function(value, format, lng) {
if (format === "uppercase") return value.toUpperCase();
if (value instanceof Date) return moment(value).format(format);
return value;
}
}
};
break;
}
i18n.init(options);
module.exports = i18n;

Related

Webpack 5 devserver doesnt recompile on file change

I'm new to Webpack configuration and having trouble setting it up and stuck on it for weeks.
I've got it to compile on start but it doesn't rebuild/recompile on changes.
I've tried to preserve log in browser console and when I save changes, it displays:
[webpack-dev-server] "src/components/Login.jsx" from static directory was changed. Reloading...
But since the code hasnt recompiled, theres no changes on the web.
If anyone can assist please.
I'm using:
NPM 6.14.17
Node v18.14.0
"webpack": "^5.47.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^4.9.3"
Script> "start": "webpack serve --env type=local"
webpack.config.js
const path = require("path");
// const moment = require('moment');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require ("html-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
let mode = "development";
let target = "web";
if (process.env.NODE_ENV === "production") {
mode = "production";
target = "browserslist";
}
const port = process.env.PORT || 3000;
module.exports = (env) => {
console.log("Passing env", env);
console.log("Target", target);
return {
mode,
stats: "normal",
optimization: {
usedExports: true, //providedExports enabled by default (only used exports are generated for each module)
},
target,
entry: './src/index.js',
output: {
filename: 'bundle.[fullhash].js',
path: path.resolve(__dirname, "dist"),
assetModuleFilename: "images/[hash][ext][query]",
publicPath: '/',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: "asset",
// loader: 'file-loader',
// type: "asset/resource",
// type: "asset/inline",
// parser: {
// dataUrlCondition: {
// maxSize: 8 * 1024,
// }
// }
},
// {
// test: /\.(s[ac]|c)ss$/i,
// use: [
// {
// loader: MiniCssExtractPlugin.loader,
// options: { publicPath: "" }
// },
// "css-loader",
// "postcss-loader",
// "sass-loader"
// ]
// },
{
test: /\.css/,
use: [
"style-loader",
"css-loader",
],
},
{
test: /\.(sass|scss)$/,
use: [{
loader: 'style-loader', // creates style nodes from JS strings
// options: { minimize: env.type == 'live' },
}, {
loader: 'css-loader', // translates CSS into CommonJS
// options: { minimize: env.type === 'live' },
}, {
loader: 'sass-loader', // compiles Sass to CSS
// options: { minimize: env.type === 'live' },
}],
},
]
},
plugins: [
// new CleanWebpackPlugin(),
// new MiniCssExtractPlugin(),
new HtmlWebpackPlugin({
template: "./src/index.html",
// favicon: 'public/favicon.ico',
}),
new BundleAnalyzerPlugin({
analyzerMode: process.env.STATS || "disabled"
}),
],
resolve: {
extensions: [".js", ".jsx"],
},
devtool: 'source-map',
devServer: {
host: 'localhost',
port: port,
liveReload: true,
watchFiles: {
paths: ['src/**/*.jsx', 'public/**/*'],
options: {
usePolling: true,
},
},
static: [
// Simple example
path.resolve(__dirname, 'static'),
// Complex example
{
directory: path.resolve(__dirname, 'static'),
staticOptions: {},
// Don't be confused with `dev.publicPath`, it is `publicPath` for static directory
// Can be:
// publicPath: ['/static-public-path-one/', '/static-public-path-two/'],
publicPath: '/static-public-path/',
// Can be:
// serveIndex: {} (options for the `serveIndex` option you can find https://github.com/expressjs/serve-index)
serveIndex: true,
// Can be:
// watch: {} (options for the `watch` option you can find https://github.com/paulmillr/chokidar)
watch: true,
},
],
hot: true,
historyApiFallback: true,
}
}
}
I've tried looking online for answers and trying different settings but haven't had much luck.
Also tried setting Hot to false but didnt work

IE explore compatible issue with Yeoman generate Office add-in

I used Yeoman for generating my Office add-in.
And got stuck with an IE11-compatible issue. here is it:
enter image description here
I check the taskpane.js file find it still using deconstruct expression which is from ES6.
enter image description here
after that, I checked the webpack.config.js file. I google it, so the babel-loader should be used to convert ES6 to ES5.
here is the file:
/* eslint-disable no-undef */
const devCerts = require("office-addin-dev-certs");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const urlDev = "https://localhost:3000/";
const urlProd = "xxxxxxx"; // CHANGE THIS TO YOUR PRODUCTION DEPLOYMENT LOCATION
async function getHttpsOptions() {
const httpsOptions = await devCerts.getHttpsServerOptions();
return { cacert: httpsOptions.ca, key: httpsOptions.key, cert: httpsOptions.cert };
}
module.exports = async (env, options) => {
const dev = options.mode === "development";
const config = {
devtool: "source-map",
entry: {
polyfill: ["core-js/stable", "regenerator-runtime/runtime"],
vendor: ["react", "react-dom", "core-js", "#fluentui/react"],
taskpane: ["react-hot-loader/patch", "./src/taskpane/index.js"],
commands: "./src/commands/commands.js",
},
output: {
clean: true,
},
resolve: {
extensions: [".ts", ".tsx", ".html", ".js"],
},
module: {
rules: [
{
test: /\.jsx?$/,
use: [
"react-hot-loader/webpack",
{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
],
exclude: /node_modules/,
},
{
test: /\.html$/,
exclude: /node_modules/,
use: "html-loader",
},
{
test: /\.(png|jpg|jpeg|gif|ico|svg)$/,
type: "asset/resource",
generator: {
filename: "assets/[name][ext][query]",
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
],
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: "assets/*",
to: "assets/[name][ext][query]",
},
{
from: "manifest*.xml",
to: "[name]" + "[ext]",
transform(content) {
if (dev) {
return content;
} else {
return content.toString().replace(new RegExp(urlDev, "g"), urlProd);
}
},
},
],
}),
new HtmlWebpackPlugin({
filename: "taskpane.html",
template: "./src/taskpane/taskpane.html",
chunks: ["taskpane", "vendor", "polyfill"],
}),
new HtmlWebpackPlugin({
filename: "commands.html",
template: "./src/commands/commands.html",
chunks: ["commands"],
}),
new webpack.ProvidePlugin({
Promise: ["es6-promise", "Promise"],
}),
new webpack.ProvidePlugin({
"React": "react",
}),
],
devServer: {
hot: true,
headers: {
"Access-Control-Allow-Origin": "*",
},
https: env.WEBPACK_BUILD || options.https !== undefined ? options.https : await getHttpsOptions(),
port: process.env.npm_package_config_dev_server_port || 3000,
},
};
return config;
};
I found it works in my code but not the library.
before:
enter image description here
after:
enter image description here
I have tried to add one more rule in config file, like:
{
test: /\.(ts|tsx)$/,
use: [
"react-hot-loader/webpack",
{
loader: "babel-loader",
options: {
presets: ["#babel/preset-typescript"],
}
},
],
exclude: /node_modules/,
},

how to reduce main.js and main.css and vendor.js divide in small chunk using webpack in react js?

I am working on performance optimization in react site last few days and I have read code-splitting documents using webpack. I have small knowledge about webpack bundling and code splitting. my webpack code.
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; // eslint-disable-line prefer-destructuring
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const DuplicatePackageCheckerPlugin = require("duplicate-package-checker-webpack-plugin");
const CompressionPlugin = require('compression-webpack-plugin'); //gzip
const BrotliPlugin = require('brotli-webpack-plugin'); //brotli
const CopyWebpackPlugin = require('copy-webpack-plugin');
const config = require('config');
const webpackConfig = {
mode: config.get('webpack.mode'),
entry: path.resolve(__dirname, 'src/index.jsx'),
output: {
path: path.resolve(__dirname, config.get('webpack.output.path')),
filename: `${config.get('webpack.output.scripts')}/[name].[hash:8].js`,
chunkFilename: `${config.get('webpack.output.scripts')}/[name].[chunkhash:8].js`,
publicPath: config.get('webpack.publicPath'),
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: [
{
loader: 'babel-loader',
},
],
exclude: /node_modules/,
},
{ // config for sass compilation
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
{
loader: "sass-loader"
}
]
},
{ // config for images
test: /\.(png|svg|jpg|jpeg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'images',
}
}
],
},
{ // config for fonts
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts',
}
}
],
},
],
},
plugins: [
(config.get('webpack.mode') === 'production') ? new CleanWebpackPlugin([
config.get('webpack.output.path'),
]) : () => {},
(config.get('webpack.mode') === 'production') ? new DuplicatePackageCheckerPlugin() : () => {},
(config.get('webpack.mode') === 'production') ?(
new CompressionPlugin({ //gzip plugin
filename: '[path].gz[query]',
algorithm: 'gzip',
test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif|png|jpg)$/,
threshold: 8192,
minRatio: 0.8
}),
new BrotliPlugin({ //brotli plugin
asset: '[path].br[query]',
test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif|png|jpg)$/, //(js|css|html|svg|txt|eot|otf|ttf|gif)$/
threshold: 10240,
minRatio: 0.6
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'public' }
]
})
):()=>{},
new HTMLWebpackPlugin({
template: path.resolve(__dirname, 'public/index.html'),
}),
new MiniCssExtractPlugin({
filename: `${config.get('webpack.output.styles')}/[name].[chunkhash:8].css`,
chunkFilename: `${config.get('webpack.output.styles')}/[name].[chunkhash:8].css`,
}),
new CaseSensitivePathsPlugin(),
new BundleAnalyzerPlugin({
analyzerMode: process.env.BA_MODE ? process.env.BA_MODE : 'disabled',
}),
],
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
minSize: 0,
name: config.get('webpack.vendorsCodeSplitting') ? (module) => {
const re = /[\\/]node_modules[\\/](.*?)([\\/]|$)/;
const packageName = module.context.match(re)[1];
return `vendors/pkg.${packageName.replace('#', '')}`;
} : 'vendors',
priority: -10,
},
default: {
name: 'default',
minChunks: 2,
reuseExistingChunk: true,
enforce: true,
priority: -20,
},
},
},
minimizer: [
(config.get('webpack.uglify')) ? new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: !!config.get('webpack.sourcemap'),
}) : () => {},
new OptimizeCSSAssetsPlugin({
cssProcessorPluginOptions: {
preset: [
'default', {
discardComments: {
removeAll: true,
},
},
],
},
}),
],
},
devtool: config.get('webpack.sourcemap'),
devServer: {
contentBase: path.resolve(__dirname, 'public'),
historyApiFallback: true,
publicPath: config.get('webpack.publicPath'),
open: config.get('webpack.open'),
overlay: true,
},
};
module.exports = webpackConfig;
I don't know what I am doing wrong with webpack configuration to improve Google page insight speed index. I also attached a screenshot bundle analysis. many third-party libraries use on a home page its impacts on page speed? thank in advanced

On starting Styleguidedist server it fails with Module parse failed: Unexpected token

Im trying to start my style guide server but it keeps throwing following error:
I believe this occurs when the babel loaders are not configured for jsx files. But this isnt true as I am able to start my project without errors. But when I try to start the style guide I end up with this.
Here is my styleguide config file
module.exports = {
title: 'Component Library',
webpackConfig: Object.assign(
{},
require("./config/webpack/webpack.dev.config.js"),
{
/* Custom config options if required */
}
),
components: "source/components/**/*.jsx",
template: {
head: {
links: [
{
rel: "stylesheet",
href:
"https://fonts.googleapis.com/css?family=Poppins:400,400i,600,600i,700,700i&display=swap"
}
]
}
},
theme: {
fontFamily: {
base: '"Poppins", sans-serif'
}
},
styles: function styles(theme) {
return {
Playground: {
preview: {
backgroundColor: '#29292e'
},
},
Code: {
code: {
fontSize: 14,
},
},
};
},
};
Here is my webpack config
var webpack = require('webpack');
var path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// const InterpolateHtmlPlugin = require('interpolate-html-plugin');
const WebpackAssetsManifest = require('webpack-manifest-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const reactLoadablePlugin = require('react-loadable/webpack')
.ReactLoadablePlugin;
const workboxPlugin = require('workbox-webpack-plugin');
module.exports = (env) => ({
mode: 'development',
entry: path.join(__dirname, '../../index.js'),
output: {
filename: '[name].bundle.[hash].js',
chunkFilename: '[name].bundle.[hash].js',
path: path.join(__dirname, '../../../build'),
publicPath: '/'
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
// cacheGroupKey here is `commons` as the key of the cacheGroup
name(module, chunks, cacheGroupKey) {
const moduleFileName = module
.identifier()
.split('/')
.reduceRight(item => item);
const allChunksNames = chunks.map(item => item.name).join('~');
return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
},
chunks: 'all'
}
}
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: path.resolve(__dirname, 'node_modules'),
loader: 'babel-loader'
},
{
test: /\.svg(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
'svg-transform-loader'
]
},
{
test: /\.png(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}
]
},
{
test: /\.(sa|sc|c)ss$/,
exclude: path.resolve(__dirname, 'node_modules'),
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new webpack.EnvironmentPlugin({
APP_ENVIRONMENT: process.env.APP_ENVIRONMENT,
API_KEY: process.env.API_KEY,
AUTH_DOMAIN: process.AUTH_DOMAIN,
DB_URL: process.env.DB_URL,
PROJECT_ID: process.env.PROJECT_ID
}),
new CleanWebpackPlugin({
path: path.join(__dirname, '../../../build')
}),
new WebpackAssetsManifest({
fileName: 'asset-manifest.json'
}),
new HtmlWebpackPlugin({
title: '<<app>>',
template: 'main.html',
minify: {
collapseWhitespace: false,
removeComments: true,
useShortDoctype: false
}
}),
new MiniCssExtractPlugin({
filename: 'style.[contenthash].css'
}),
new CopyPlugin([
{
from: 'public',
to: 'public'
}
]),
new ProgressBarPlugin({
format: ' build [:bar] ' + ':percent' + ' (:elapsed seconds)' + ' :msg'
}),
new reactLoadablePlugin({
filename: './react-loadable.json'
}),
new workboxPlugin.InjectManifest({
swSrc: path.join(__dirname, '../../public/service-worker.js')
})
],
devServer: {
contentBase: path.join(__dirname, '/'),
filename: 'main.html',
compress: true,
port: 3000,
historyApiFallback: true,
disableHostCheck: true,
useLocalIp: true,
host: '0.0.0.0'
},
devtool: 'eval-source-map'
});
The problem was with the webpack file I was exporting the webpack configurations as a function.
Earlier:
module.exports = (env) => ({
....your webpack configurations
})
Instead of exporting everything as a function I exported it as
Now:
module.exports = {
....your webpack configurations
}
But can someone tell me why the earlier implementation didnt work?

React Loadable Problem In My React Website

Can someone help me with the Issue in my React Website?
We have used react-loadable for chunks whenever we deploy it on production environment the website get stuck on the loading part. Below is the URL
URL WITH LOADABLE: http://fcastage.surge.sh/
Any help will be appreciated.
We have tried making the website using react loadabale and without react loadable. But to make the website fast and load in chunks we have to use loadable . The react loadable is working fine with Development Environment but its not working when I am switching to Production.
Below is the Config File for Production
const HtmlWebpackPlugin = require("html-webpack-plugin");
//const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = require("path")
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { ReactLoadablePlugin } = require('react-loadable/webpack')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
mode: "production",
entry: "./app/index.js",
output: {
path: path.resolve(__dirname, "./build"),
filename: '[name].bundle.js',
chunkFilename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{
//because remove style-loader,my css can't work
loader: "css-loader",
options: {
importLoaders: 1,
modules: true,
localIdentName: "[local]"
} // translates CSS into CommonJS
},
{
loader: "less-loader" // compiles Sass to CSS
}
]
})
},
{
test: /\.(jpe?g|png|gif|svg|ico)$/i,
use: [
{
loader: "url-loader",
options: {
outputPath: "assets/",
limit: 10 * 1024
}
}
]
},
{
test: /\.(woff|woff2|eot|ttf)$/i,
use: [
{
loader: "url-loader",
options: {
outputPath: "assets/"
}
}
]
}
]
},
optimization : {
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
}
}
}
// minimizer: [
// new UglifyJsPlugin({
// uglifyOptions: {
// compress: {
// unused: true,
// dead_code: true,
// warnings: false
// }
// },
// sourceMap: true
// }),
// ]
},
plugins: [
new HtmlWebpackPlugin({
template: "./app/index.html",
hash: true,
filename: "index.html"
}),
//for surge.sh
new HtmlWebpackPlugin({
template: "./app/index.html",
hash: true,
filename: "200.html"
}),
new CleanWebpackPlugin(),
new ExtractTextPlugin("main.css"),
new webpack.DefinePlugin( {'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.DEBUG': JSON.stringify(process.env.DEBUG) } ),
new ReactLoadablePlugin({
filename: path.resolve(__dirname, "build/react-loadable.json")
})
],
};

Resources