Webpack: Bundle required css files - css

Being a newbie to Webpack, I'm following the discussion: Recomended way to require CSS in webpack by:
Configuring my Webpack configurations with
{
test: /(\.css|\.scss)$/,
loaders: ['style-loader', 'css-loader?sourceMap', 'postcss-loader', 'sass-loader?sourceMap'],
},
Requiring css files in my code:
require('./style1.css');
require('./style2.css');
But the two css files above will not be bundled together. How to instruct Webpack to bundle all required css files?

By default webpack will not bundle your css, it will create inline style tag in HTML and place your css there. For extract all your css and bundle into one css file you nee extract text plugin
for webpack 2
npm install --save-dev extract-text-webpack-plugin
for webpack 1
npm install --save-dev extract-text-webpack-plugin#1.0.1
In webpack 2
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
}
Webpack 1
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
]
},
plugins: [
new ExtractTextPlugin("styles.css")
]
}
Read more https://github.com/webpack-contrib/extract-text-webpack-plugin

As I saw in your Webpack configuration entires, you are instructing Webpack to bundle your css files inject then as inline css by using css-loader and style-loader.The css-loader takes a CSS file and reads off all its dependencies whilst the style-loader will embed those styles directly into the markup as tag in the of the document.
Personally, just to keep things clean, I’d prefer to have a separate CSS file rather than adding all the code inline. To do that we’ll need to use a Webpack plugin called extract-text-webpack-plugin which moves every require('style.css') in entry chunks into a separate css output file. We have to install that with npm:
for webpack 2
npm install --save-dev extract-text-webpack-plugin
for webpack 1
npm install --save-dev extract-text-webpack-plugin#1.0.1
Now we can update our webpack.config.js file again by requiring it and placing our CSS loader into it:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './src',
output: {
path: 'build',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.js/,
loader: 'babel',
include: __dirname + '/src',
},
{
test: /\.css/,
loader: ExtractTextPlugin.extract("css")
}
],
},
plugins: [
new ExtractTextPlugin("styles.css")
]
};
it then creates a styles.css file for us! We can now add this stylesheet file in the
<link rel="stylesheet" href="build/styles.css">

Related

How to merge several css files into one in webpack 4?

I want to compose one main.css file from several css files. How can I make this using webpack 4?
This is my webpack.config.js:
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'public/app.js'),
output: {
path: path.resolve(__dirname, 'public'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['#babel/plugin-proposal-class-properties']
}
}
}
]
},
plugins: []
};
Webpack has some awesome tools available for merging files into one, I would suggest you using .scss files and let those merge into css files. However that is your own preferred issue.
Please take a look at this plugin to merge multiple css files into one.
https://github.com/oklas/merge-webpack-plugin
A better understanding can be found at this post as well: https://medium.com/trabe/multiple-css-bundles-with-webpack-75f263095f09

Webpack build successfull but styles.css file style is not reflecting

I am developing a web application in angular 5.Now I have included webpack 4 in my application.But There is a problem all styles written in styles.css file are not reflecting in the build created from webpack.
Need solution for this problem.
Below is my webpack.common.js file which is used for loading diffrent types of files present in my application build always succeed but the styles.css code is not reflection on my site when it gets loaded in browser.But code written in components .scss file reflects properly i have searched a lot but did not find any solution for this issue why is is happening.
import styles from './styles.css';
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfill': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loader: ['awesome-typescript-loader','angular2-template-loader','angular-router-loader'
],
exclude:[/node_modules/]
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/images/[name].[hash].[ext]'
},
{
test: /\.(css|scss)$/,
include: helpers.root('src', 'app'),
loaders: ['css-loader']
},
{
test: /\.js$/,
include: helpers.root('src', 'app'),
loader: 'babel-loader',
exclude:[/node_modules/],
query:{
presets:['es2015']
}
}
]
},
plugins: [
// Workaround for angular/angular#11580
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)#angular/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new ExtractTextPlugin("src/styles.css"),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
You should import your css stylesheet using #import from your main css/scss stylesheet.
Do NOT import a css file as a javascript module from the webpack config file. This has no sense.

Error Loading CSS with Webpack and Babel

I'm building a SSR React App with Webpack3 and Babel6 but when I run the server, it cannot find any css file (Error: Cannot find module './file.css').
Here is my folder structure so far:
src/
|-components/
|-App/
|-App.css
|-App.jsx
App.jsx
....
import './App.css';
....
webpack.config.js
....
module.exports: { loaders: [
....
{
test: /\.css$/,
loader: ['style-loader', 'css-loader'], // I have loaders installed and included in package.json devDependencies
include: path.join(__dirname, 'src'),
exclude: /node_modules/
}
....
]}
Any ideas?
By default when you install packages locally, they go into node_modules folder in your project directory, therefore style-loader and css-loader are also included there. From your webpack.config.js file you are excluding this packages, which are needed in compiling your css assets. just remove the exclude line and every thing would be fine.
your webpack.config.js file would look like this.
webpack.config
....
module.exports: { loaders: [
....
{
test: /\.css$/,
loader: ['style-loader', 'css-loader'],
include: path.join(__dirname, 'src'),
}
....
]}

Webpack throwing error on SCSS #import SCSS

I'm trying to process multiple SCSS files into a single external CSS file in Webpack (3.6.0) except I'm encountering issues around the parsing of the #import statements.
Entry index.js contains:
import './styles/main.scss';
Entry SCSS:
#import 'reset.scss';
#import 'global.scss';
#import 'fonts.scss';
#import 'system.scss';
Current webpack:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js'
},
context: path.resolve(__dirname),
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js',
},
plugins: [
new CleanWebpackPlugin(['app']),
new HtmlWebpackPlugin({
title: 'Minimum-Viable',
filename: 'index.html',
template: './public/index.html',
}),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'es2015',
'react',
],
plugins: ['transform-class-properties'],
},
},
},
{
test: /\.scss$/,
include: [
path.resolve(__dirname, 'styles')
],
use: [
{loader:'style-loader'},
{loader:'css-loader'},
{loader:'sass-loader'}
]
},
],
},
resolve: {
extensions: ['.js','.scss']
}
};
The Error being thrown is:
ERROR in ./src/styles/main.scss Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type. | #import 'reset.scss';
Any pointers gratefully received.
I managed to reproduce the error and it seems to come from:
include: [
path.resolve(__dirname, 'styles')
],
The path is the issue cause the loader searches for /styles in ./styles but looking at your entry point:
entry: {
app: './src/index.js'
},
It should actually be ./src/styles so:
include: [
path.resolve(__dirname, 'src', 'styles')
],
with:
include: [
path.resolve(__dirname, 'styles')
],
you are instructing webpack to use your loader chain only on files residing in your styles folder.
reset.scss looks like a node dependency usually stored in your node_module, which is excluded from SASS processing by the include option.
Try to remove your SASS include option or to extend it in order to include node_folder or the specific module imported by your styles.
I basically have the same config as you, except for two things:
{
test: /\.scss$/,
exclude: /node_modules/,
use: ["style-loader", "css-loader", "sass-loader"]
}
If your webpack is in a different folder compared to your project root, __dirname may not work out for you. You might need to remove that statement all together or change it to process.cwd(). I can give you another hint and that may be that you are missing the node-sass package. Secondly, you are probably not using the right syntax for webpack version 2 or 3 as shown in the use key.
Have you tried Extract text webpack plugin
https://github.com/webpack-contrib/extract-text-webpack-plugin
Basically it will collect all of your styles files(imported in your code) and pack it to bundled css which you can then just link to your html.
Did you try this way?
index.js:
import './styles/main.scss';
import './styles/reset.scss';
import './styles/global.scss';
import './styles/fonts.scss';
import './styles/system.scss';

How to use autoprefixer for external css files - webpack

I have all the css files inside ${ROOT}/resource/css/. While building using webpack, I want to copy all the css files to ${ROOT}/build/css/ with desired vendor prefixes added to all the css rules.
Currently I am using copywebpackplugin to copy all the css files as is to ${ROOT}/build/css/. I am struggling to add add a step to add vender prefixes. Please help.
Below the my webpack config:
config = {
entry: {
"new": "./resources/js/new",
"view": "./resources/js/view",
"edit": "./resources/js/edit",
"preview": "./resources/js/preview",
"sidebar": "./resources/js/sidebar",
"frame": "./resources/js/frame"
},
output: {
filename: "[name].js",
path: "build/js"
},
module: {
loaders: [
{test: /\.js$/, loaders: ["babel-loader", "eslint-loader"]}
]
},
plugins: [
new CopyWebpackPlugin([{
from: './resources/css/*.css',
to: './build/css/[name].css'
}])
]
}

Resources