Add sass loader to the webpack already using react - reactjs

I have this configuration in my webpack and I need to add sass-loader,
I already added the dependencies using
npm install sass-loader sass webpack --save-dev
But I'm confused where I include the sass loader and the documentation settings.
Now how to add to my webpack?
'use strict'
const path = require('path')
const webpack = require('webpack')
const validate = require('webpack-validator')
module.exports = validate({
devtool: 'source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
path.join(__dirname, 'src', 'index'),
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
preLoaders: [{
test: /\.js$/,
exclude: /node_modules/,
include: /src/,
loader: 'standard'
}],
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
include: /src/,
loader: 'babel'
}],
}
})

I assume you want to add sass-loader in order to support scss files.
Add a new item to the loaders/rules array:
If you use webpack < v3:
loaders:[
...,
{
test: /\.(scss|sass)$/,
loader: 'style-loader!css-loader!sass-loader'
}
]
For webpack > v3 add a rule like this:
rules:[
...,
{
test: /\.(scss|sass)$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
}
]
For more details look here https://webpack.js.org/loaders/sass-loader/

Related

Can I delete parts of bootstrap.min.css that I'm not using?

I have a small React app that I'm minifying with Webpack, and I noticed that ~80% of my minified index.js file is just Bootstrap css that I'm not using, plus Webpack warns me that my entry file is too big (~900kb vs ~250kb recommended). I found a few answers here from a long time ago that said to remove parts of bootstrap.min.css file that I don't need, and I'm wondering if that's still the recommended solution for a React app using react-bootstrap?
This is my production webpack config:
const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
module.exports = {
entry: '/src/index.tsx',
output: {
path: path.resolve(__dirname, 'prod'),
},
mode: 'production',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
},
{
test: /\.css$/,
include: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules/react-toastify/dist'),
path.resolve(
__dirname,
'node_modules/bootstrap/dist/css/bootstrap.min.css'
),
path.resolve(
__dirname,
'node_modules/react-grid-layout/css/styles.css'
),
path.resolve(
__dirname,
'node_modules/react-resizable/css/styles.css'
),
],
use: ['style-loader', 'css-loader'],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: 'ts-loader',
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
}),
new FaviconsWebpackPlugin('./src/logo.png'),
],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
}
And at the top of my App.tsx file I have
import 'bootstrap/dist/css/bootstrap.min.css'
Ok so I was able to (I think) accomplish what I was asking. I first tried to follow the instructions here:
https://medium.com/dwarves-foundation/remove-unused-css-styles-from-bootstrap-using-purgecss-88395a2c5772
So running purgecss --css [path to bootstrap css] ---content src/index.html --output public did create very minified CSS files, but either I did something wrong or purgecss removed too much, because the bootstrap styles didn't seem to be applied to anything.
Instead, I installed MiniCssExtractPlugin, and pointed webpack to the full bootstrap.min.css file. Running webpack with the below (updated) webpack.prod.js config file reduced the entry file size from ~900kb to ~360kb, which is still above the recommended limit but is about 1/3 the size of the entry before these changes.
Edit: and it also seems good that now the css styles are in their own actual main.css file, rather than for some reason being inside main.js, which is how it was before adding MiniCssExtractPlugin.
const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: '/src/index.tsx',
output: {
path: path.resolve(__dirname, 'prod'),
},
mode: 'production',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
},
{
test: /\.css$/,
include: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'public')
],
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: 'ts-loader',
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
}),
new MiniCssExtractPlugin({filename: "[name].css", chunkFilename: "[id].css"}),
new FaviconsWebpackPlugin('./src/logo.png'),
],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
}

Module parse failed getting error in webpack

I am working on webpack in react, when i run this command npx webpack --config webpack.config.js , i am getting below error
ERROR in ./node_modules/react-toastify/dist/ReactToastify.css 1:0
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
here i have attached my webpack.config.js , can anyone please help me why i am getting this error ?
const path = require('path')
module.exports = {
entry: path.resolve(__dirname, 'src', 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(jsx|js)$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-env', {
"targets": "defaults"
}],
'#babel/preset-react'
]
}
}]
}
]
}
}
You'll need to install style-loader and css-loader:
npm install --save-dev style-loader css-loader
Then add the loaders to your webpack config. For example:
webpack.config.js
const path = require('path')
module.exports = {
entry: path.resolve(__dirname, 'src', 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(jsx|js)$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-env', {
"targets": "defaults"
}],
'#babel/preset-react'
]
}
}]
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
}
]
}
}
Try adding
"babel": { "presets": ["#babel/preset-env"] }
To the end of your package.json file - after devDependencies (you may need to add #babel/preset-env via Yarn as well.)

Getting error with the newly configured webpack 2

I am trying to configure webpack 2 for my react development app. Seems like there is something I am missing below is my webpack.config.dev
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var loaders = [
{
loader: 'css-loader',
options: {
modules: true
}
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
];
export default {
resolve: {
extensions: ['', '.js', '.jsx', '.json']
},
devtool: 'eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
entry: {
app: path.resolve(__dirname, 'src/index.js'),
vendor: ["react", "react-dom"]
},
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
path: path.resolve(__dirname, 'dist'), // Note: Physical src are only output by the production build task `npm run build`.
publicPath: '/',
filename: "[name].entry.chunk.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: '[name].[hash].js', }),
new ExtractTextPlugin("[name].css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'), // Tells React to build in either dev or prod modes. https://facebook.github.io/react/downloads.html (See bottom)
__DEV__: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({ // Create HTML file that includes references to bundled CSS and JS.
template: path.join(__dirname, './src/index.html'),
filename: 'index.html',
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true
},
})
],
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel']},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
{test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
{test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: loaders,
}) },
{test: /\.json$/, loader: "json"}
]
},
};
This is my github repo https://github.com/sourabh-garg/Webpack-2-starter-kit please clone it and and run npm install followed by npm start.
When I run it I get
ERROR in ./src/index.js
Module build failed: SyntaxError: Unexpected token (6:0)
render(
"<h1>Hello World!</h1>", document.getElementById('app')
);
Please let me know what I am missing.

Webpack ReactJS file creation

I am trying out ReactJS with Webpack, hot updating, and React-Router. Below is my
webpack.config.js code. For some reason there are a bunch of json files being created at the very top of the file tree. For example, fb43026df6c9e1823c07.hot-update.json
Files end with .hot-update.json
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:5000',
'webpack/hot/dev-server',
'./scripts/index'
],
output: {
path: __dirname,
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
extensions: ['', '.js']
},
devtool: 'eval-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.jsx?$/,
loaders: ['babel'],
include: path.join(__dirname, 'scripts')
}
]
}
};
This is the file that Webpack's hotModuleReplacementPlugin is reading from every time you make a change and save it. It's making new bundles of your app for your front end to receive.

CSS loading throw error using webpack

I have implemented webpack config like
/* eslint-disable no-var */
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'webpack-hot-middleware/client',
'./src/main'
],
devtool: 'eval-source-map',
output: {
path: __dirname,
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
},
{
test: /\.css$/, // Only .css files
loader: 'style!css' // Run both loaders
}
]
}
};
and I have installed the css-loader style-loader for loding the css on my page and I am using the bootstrap.min.css as below
require('../../node_modules/bootstrap/dist/css/bootstrap.min.css');
it's throw error like
Bootstrap is using the Glyphicons font. You also need to have a loader for the font:
{
test: /\.woff$/,
loader: 'url?limit=100000'
}
Source: christianalfoni.github.io/react-webpack-cookbook/Inlining-fonts
Or:
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
}
Source: stackoverflow.com/a/31183889/2378031

Resources