webpack to bundle library antd - reactjs

I'm using and design library for my react application.
And I've faced with huge imports, that hurts my bundle (currently 1.18 mb in minified version because of ant-design lib).
var path = require('path');
var webpack = require('webpack');
var config = {
entry: {
vendor: ['react', 'react-dom','antd'],
app: './Scripts/js/app.js',
},
output: {
path: path.join(__dirname, "Scripts/bundles"),
filename: "[name].bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', "less-loader"]
},
{
loader: 'babel-loader',
exclude: /node_modules/,
test: /\.js$/,
options: {
presets: ['es2015', 'react', 'stage-0'],
},
},
]
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.optimize.UglifyJsPlugin({ minimize: true }),
new webpack.optimize.CommonsChunkPlugin({
name: ['vendor'],
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
}
module.exports = config;
And my app
import React from 'react'
import ReactDOM from 'react-dom'
import { DatePicker } from 'antd';
ReactDOM.render(<DatePicker />, document.getElementById('container'));
Those few components are certainly not 1.2M together.

Install babel-plugin-import and add it to the babel-loader options:
options: {
presets: ['es2015', 'react', 'stage-0'],
"plugins": [
["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }]
]
}
If you don't want to use the babel plugin, you'd have to import it this way:
import DatePicker from 'antd/lib/date-picker';
import 'antd/lib/date-picker/style/css';

Related

How to configure css modules in my React app

Im not using the create react app project. Here is my webpack.base.js (someone else set this up so im just working off what i have)
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: "./src/index.tsx",
target: "web",
mode: "development",
output: {
filename: "[name].[chunkhash].bundle.js",
path: path.resolve(__dirname, "/opt/valkyrie/html"),
clean: true
},
watchOptions: {
ignored: '**/node_modules',
},
resolve: {
modules: ["src", "node_modules"],
extensions: [
".tsx",
".ts",
".js",
".jsx",
".svg",
".css",
".json",
".mdx",
".png",
".scss",
".sass"
],
alias: {
react: path.resolve('./node_modules/react')
}
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '/public/icons/[name].[ext]'
}
},
],
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Spectrum App",
template: __dirname + "/public/index.html",
inject: "body",
filename: "index.html",
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css",
}),
]
};
Can someone tell me how I turn on css modules? Googling around i see a number of posts about turning it on for the create react app but they mention existing settings that i dont have in mine.
Im using React 17.0.2
Add this to webpack module
module: {
loaders: [
{
test: /\.css/,
loaders: ['style', 'css'],
include: `${__dirname}/src`,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
and please rename the css files as component_name.module.css and import the css file in jsx/js as import styles from './component_name.module.css';

unable to import react component from library

After going through almost all the answers related to this topic I had no luck so have to create a new question.
Problem Statement :
I have a library of components (module) that I want to import inside my react application which has an export syntax like(working in another app) :
export * from 'button'; // this returns jsx component
Now, in my application I am using this as :
import {button} from ./library; // this is the bundled module where button component exists.
When I do this Webpack gives me an error :
(function (exports, require, module, __filename, __dirname) { export * from './button';
^^^^^^
SyntaxError: Unexpected token export
I am using Webpack 4 and babel 7 with these configurations :
webpack.config.js
//this is exports.
module.exports = {
entry: {
client: ['whatwg-fetch', './client/index.js', 'webpack-hot-middleware/client']
},
optimization: {
minimizer: [new OptimizeCSSAssetsPlugin({})]
},
output: {
path: path.resolve(__dirname, `dist/client/${pkg.version}`),
filename: '[name].js',
publicPath: `/myApp/${pkg.version}`
},
devtool: ifProduction('nosources-source-map', 'source-map'),
resolve: {
modules: [path.resolve('./client'), path.resolve('./node_modules')]
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.less$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
},
{
test: /\.(ttf|eot|svg|woff|woff2?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader?name=fonts/[name].[ext]'
},
{
test: /\.(png|jpg|ico|svg|eot|ttf)$/,
loader: 'url-loader'
}
]
},
mode,
plugins: [
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin(),
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: '../report.html'
})
]
};
babel.config.js
// prettier-ignore
module.exports = {
presets: [
'#babel/preset-env',
'#babel/preset-react',
],
plugins: [
'#babel/plugin-transform-spread',
'react-hot-loader/babel',
'babel-plugin-syntax-export-extensions',
'#babel/plugin-proposal-export-namespace-from',
'#babel/plugin-syntax-export-namespace-from',
'#babel/plugin-syntax-export-default-from',
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-proposal-class-properties',
['#babel/plugin-transform-runtime',
{
regenerator: true,
},
],
],
env: {
development: {
presets: [
'#babel/preset-env', ['#babel/preset-react', { development: true } ],
],
},
test: {
presets: [['#babel/preset-env'], '#babel/preset-react'],
},
},
};
I am not sure what's going wrong, Any help would be much appreciated.
Thanks.

Why is my Webpack not working for CSS Modules

I am trying to use CSS Modules to style my react components. I have sass-loader configured in my webpack build, however, the stylings do not get applied to my components. Please see below for a component example and my webpack config. Is there something I am doing wrong in webpack that is causing this issue or something I am doing wrong in how I am writing my component? Thanks!
sampleComponent.js:
import React from 'react';
import styles from './sampleComponent.scss';
const SampleComponent = (
<p className={styles.description}>This is some text</p>
);
export default SampleComponent;
sampleComponent.scss:
.description {
color: blue;
font-size: 20px;
}
webpack.common.js:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');
const DIST_DIR = path.resolve(__dirname, "dist");
const SRC_DIR = path.resolve(__dirname, "src");
const config = {
entry: [
"babel-polyfill",
`${SRC_DIR}/app/index.js`,
`${SRC_DIR}/app/assets/stylesheets/application.scss`,
`${SRC_DIR}/app/components/index.scss`,
"font-awesome/scss/font-awesome.scss",
"react-datepicker/dist/react-datepicker.css",
"rc-time-picker/assets/index.css",
"react-circular-progressbar/dist/styles.css",
"#trendmicro/react-toggle-switch/dist/react-toggle-switch.css",
],
output: {
path: `${DIST_DIR}/app/`,
filename: "bundle.js",
publicPath: "/app/"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
failOnWarning: false,
failOnError: true
}
},
{
test: /\.js$/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'stage-2']
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader',
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: ['file-loader?context=src/images&name=images/[path][name].[ext]', {
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
pngquant: {
quality: '75-90',
speed: 3,
},
},
}],
exclude: path.resolve(__dirname, "node_modules"),
include: __dirname,
},
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
// loader: "url?limit=10000"
use: "url-loader"
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
use: 'file-loader'
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "application.css"
}),
new webpack.DefinePlugin({
'process.env.INTERNAL': JSON.stringify(process.env.INTERNAL),
}),
],
};
module.exports = config;
You could do something like
import React from 'react';
import './sampleComponent.scss';
const SampleComponent = (
<p className="description">This is some text</p>
);
export default SampleComponent;

How Instagram doesn't load any css?

I am little bit curios that how instagram doesn't load any css but rendering the styles is that a webpack configuration if so how to do it
How to configure my webpack file to act like that
My production webpack
import path from 'path';
import webpack from 'webpack';
import qs from 'querystring';
import autoprefixer from 'autoprefixer';
import AssetsPlugin from 'assets-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
const root = process.cwd();
const src = path.join(root, 'src');
const clientSrc = path.join(src, 'client');
const build = path.join(root,'build');
const clientInclude = [clientSrc];
const vendor = [
'react',
'react-dom',
'react-router',
'react-redux',
'redux',
'react-router-dom'
];
export default {
context: src,
entry: {
app: [
'babel-polyfill/dist/polyfill.js',
'./client/client.js'
],
vendor
},
output: {
path: build,
filename: '[name].js'
},
resolve: {
extensions: ['.js'],
modules: [src, 'node_modules'],
unsafeCache: true
},
node: {
dns: 'mock',
net: 'mock'
},
plugins: [
new webpack.NamedModulesPlugin(),
new ExtractTextPlugin('[name].css'),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: "vendor.js",
minChunks: Infinity
}),
new webpack.optimize.AggressiveMergingPlugin(),
/* minChunkSize should be 50000 for production apps
* 10 is for this example */
new webpack.optimize.MinChunkSizePlugin({minChunkSize: 50000}),
new webpack.optimize.UglifyJsPlugin({compressor: {warnings: false}, comments: /(?:)/}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({
'__CLIENT__': true,
'__PRODUCTION__': true,
'process.env.NODE_ENV': JSON.stringify('production')
})
// new webpack.optimize.DedupePlugin(),
// new webpack.optimize.UglifyJsPlugin(),
// new webpack.optimize.OccurrenceOrderPlugin()
],
module: {
loaders: [
{test: /\.(png|j|jpeg|gif|svg|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 10000
}
}
},
// JavaScript
{test: /\.js$/,
loader: 'babel-loader',
include: clientInclude
},
// CSS
{test: /\.css|less$/,
include: clientInclude,
loaders: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{loader: 'css-loader',
options: {
root: src,
modules: true,
importLoaders: 1,
localIdentName: '[name]_[local]_[hash:base64:5]'
}}
]})
}
]
}
}

React bootstrap not rendering style

Bootstrap styles not rendering when everything is setup fine. I have install react-bootstrap and imported bootstrap css, but i cannot get the style to render. I can make it work through a create-react-app boilerplate. I suspect that it has something to do with my bootstrap. this is my webpack.config file:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devServer: {
inline: true,
contentBase: './src',
port: 3000
},
devtool: 'cheap-module-eval-source-map',
entry: './dev/js/index.js',
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015', 'react', 'stage-0']
},
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
}
]
},
output: {
path: 'src',
filename: 'js/bundle.min.js'
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin()
]
};

Resources