unable to load css in react js - css

my all css files placed under src/assets/css/* and i am trying to import or load css file inside my component, i have tried to load css with below webpack configuration
Webpack file
{ test: /\.css$/, loader: "style-loader!css-loader" }
Component
import './../../assets/css/bootstrap.min.css';
Also tried to load css in index.html file like <link rel="stylesheet" href="/src/assets/css/bootstrap.min.css">
Also, is there a way if i have 5-6 css files by which i dont need to load all files in every component like if we can add in <head> tag

Here is my webpack.config file. I have used foundation instead of bootstrap but the webpack configuration is similar.
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'script!jquery/dist/jquery.min.js',
'script!foundation-sites/dist/js/foundation.min.js',
'./app/app.jsx'
],
externals: {
jquery: 'jQuery'
},
plugins:[
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
})
],
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
root: __dirname,
modulesDirectories: [
'node_modules',
'./app/components',
'./app/api'
],
alias: {
applicationStyles: 'app/styles/app.scss',
actions: 'app/actions/actions.jsx',
reducers: 'app/reducers/reducers.jsx',
configureStore: 'app/store/configureStore.jsx'
},
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0']
},
test:/\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
},
sassLoader:{
includePaths: [
path.resolve(__dirname, './node_modules/foundation-sites/scss')
]
},
devtool: 'cheap-module-eval-source-map'
};
And yes you can bundle the css in one file with webpack and import it in the root component.
Check my github repo for more details- https://github.com/hmachaharywork/ReactTodo

Use Extract text plugin. Only import this plugin in your webpack.conf.js
const ExtractTextPlugin = require("extract-text-webpack-plugin");
and refactor your rule like:
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
Finally, push new instance in plugin list:
plugins: [
new ExtractTextPlugin("styles.css"),
]

Related

How to stop WebPack from including CSS file in the html even though it is already included in the produced js file

I am using WebPack to build a chrome extension. I import the css file in the popup.js file and it correctly styles my page but bundler also inserts the css file to the html which is unnecessary if I know correctly since it is injected to the output js file. Because the css file is included in the hmtl, I get a "Failed to load resource: net::ERR_FILE_NOT_FOUND". I want to know how to exclude the CSS file from the html and basically dont have the following line.
<link rel="stylesheet" href="popup-styles.css" />
This is my webpack.config.js file.
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
entry: {
popup: "./src/popup.js",
background: "./src/background.js",
content: "./src/content.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
},
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/popup.html",
filename: "popup.html",
chunks: ["popup"],
}),
new CopyPlugin({
patterns: [{ from: "public" }],
}),
],
};

Compile CSS and JS in difference files / WEBPACK

For 2 days I have been trying to compile the js and css file to a separate file because now everything is together. Does anyone have any idea how this can be solved?
I would be very grateful for your help.
There is my code webpack.config.js
const path = require('path');
const webpack = require('webpack');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'src/dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
{
loader: "css-loader",
options: {
url: false
}
},
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
},
]
},
plugins: [
new BrowserSyncPlugin({
// browse to http://localhost:3000/ during development,
// ./public directory is being served
host: 'localhost',
port: 3000,
files: ['./src/*.html'],
server: { baseDir: ['src'] }
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
};
I think MiniCssExtractPlugin is what you are looking for.
It takes the output of css-loader and create .css bundles. It takes care of downloading them in the browser (by pushing a section of code in webpack runtime code), and also yeah, it minifies the .css :).
Simple usage:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
};
Yes you are right. Style-loader creates javascript snippets that later in runtime creates .css rules and push them to the browser global css scope.

Font-awesome 5 doesn't work with webpack when installing with npm

I want to install Font-awesome with npm so that it will work with webpack and babel.
I installed font-awesome with npm via
npm install --save-dev #fortawesome/fontawesome-free
And added this to the top of my index.js
import '#fortawesome/fontawesome-free/js/fontawesome'
import '#fortawesome/fontawesome-free/js/solid'
import '#fortawesome/fontawesome-free/js/regular'
import '#fortawesome/fontawesome-free/js/brands'
When I'm trying to add icons to my html e.g.
<i class="fas fa-like"></i>
It just shows a circle with a question mark
My webpack config
const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './src/index.js']
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
mode: 'development',
target: 'web',
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: 'html-loader',
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(scss)$/,
use: [{
loader: 'style-loader', // inject CSS to page
}, {
loader: 'css-loader', // translates CSS into CommonJS modules
}, {
loader: 'postcss-loader', // Run post css actions
options: {
plugins: function () { // post css plugins, can be exported to postcss.config.js
return [
require('precss'),
require('autoprefixer')
];
}
}
}, {
loader: 'sass-loader' // compiles Sass to CSS
}]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: './src/html/index.html',
filename: './index.html',
excludeChunks: ['server']
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
};
My .babelrc
{
"presets" : ["#babel/preset-env"]
}
P.s. Everything works fine, it is just that my font-awesome icons aren't displaying properly.
You are using an invalid icon because there is no fa-like, you are probably looking for fa-thumbs-up instead:
<script src="https://use.fontawesome.com/releases/v5.8.1/js/all.js"></script>
<i class="fas fa-like"></i>
<i class="fas fa-thumbs-up"></i>
You can easily seach for icons here: https://fontawesome.com/icons?d=gallery&q=like

Webpack and boostrap, remove styles from style tag

I'm new with Webpack. Using webpack 4.26.
I was trying to install bootstrap. I'v install it but css styles wasn't build in a separate file. I'v solved this problem and now my config looks like this:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: './app/index.js',
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.(png|svg|jpe?g|gif)$/,
exclude: /svg[\/\\]/,
loader: 'file-loader',
options: {
name: 'images/[name].[ext]'
}
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'style.css',
})
]
};
Index.js:
'use strict'
import 'bootstrap';
import './index.scss';
index.scss
#import "~bootstrap/scss/bootstrap";
So now I have a separate file 'style.css' with all bootstrap styles, but, as I understand styles still included to bundle and rendered into tag.
How can I remove it from bundle?

Webpack Automatically import css from node modules

TL;DR: Is there any way to automatically scan or automatically import all stylesheets used by our web packages, from our node_modules folder?
I am working on a project that uses angularJS as its MVC framework, and we are currently in the process of migrating to use webpack. I currently wrote the following configuration:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const bbProperties = require('./webpack.properties');
const appRoot = __dirname + "/../../..";
console.log('__dirname:', __dirname);
module.exports = {
entry: {
app: appRoot + bbProperties.app.entryScript,
login: appRoot + bbProperties.login.entryScript
},
output: {
path: appRoot + bbProperties.distFolder,
publicPath: "dist",
filename: "js/[name].bundle.js",
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2017']
}
},
{
test: /\.css$/,
//exclude: /node_modules/,
use: [
{loader: 'style-loader'},
{loader: 'css-loader', query: {importLoaders: 1}},
{loader: 'postcss-loader', query: {config: {path: __dirname+'/postcss.config.js'}}}
]
},
{
test: /\.(png|jpg|jpeg|gif)$/,
exclude: /node_modules/,
use: [
{
loader: 'file-loader',
options: {
name:'[name].[ext]',
outputPath:"/assets/images/"
}
}
]
},
{
test: /\.(ttf|eot|woff|woff2|svg)($|\?.*$)/,
exclude: /node_modules/,
use: [
{
loader: 'file-loader',
options: {
name:'[name].[ext]',
outputPath:"/assets/fonts/"
}
}
]
},
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
moment: "moment"/*,
_: "lodash",
"window._": "lodash",
angular: "angular"*/
}),
//Creates an html file with all bundles injected as <script> tags
new HtmlWebpackPlugin({
chunks: ['app'],
filename: '../angular-app/menu/' + bbProperties.app.outputFile,
hash: "true", //cache busting
template: appRoot + bbProperties.app.location + "/" + bbProperties.app.inputFile
}),
//Second html bundle for login page
new HtmlWebpackPlugin({
chunks: ['login'],
filename: '../'+bbProperties.login.outputFile,
hash: "true", //cache busting
template: appRoot + bbProperties.login.location + "/" + bbProperties.login.inputFile
})
],
stats: {colors: true},
devtool: 'source-map',
node: {
fs: "empty"
}
};
As far as I understand, webpack will start creating a bundle from each entry file, adding any file it encounters in import statements recursively.
I also understand that I can require a package from my node_modules directory, and that in such a case webpack will search for a package.json file and import the file specified in the 'main' property of that file.
Lets say we are dependant on several packages, components and frameworks (for example: angular-ui-grid, angular-material etc...), I know I can manually import their CSS files using css loaders by importing them into my JS code.
Is there any way to automatically scan or automatically import all stylesheets used by those packages, from our node_modules folder?

Resources