How to add CSS configuration in reactjs Project? - css

I've written the webpackconfig but css doesn't seem to work properly and it is throwing and error. Following are my file's contains.
My webpack.config.js:
module: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["react", "es2015", "stage-2"]
}
}
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
}
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
}
]
},
plugins: [
new ExtractTextPlugin("style.css", {
allChunks: true
})
]
};
and in my Index.js I've added as :
import '../assets/css/style.css';
Package.json :
{
...
"dependencies": {...
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.3",
"css-loader": "^0.28.7",
"style-loader": "^0.19.0"
}
}

As per our chat, this is what your webpack.config.js file is as below:
var path = require("path");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var config = {
entry: SRC_DIR + "/app/index.js",
output: {
path: DIST_DIR + "/app",
filename: "bundle.js",
publicPath: "/app/"
},
module: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["react", "es2015", "stage-2"]
}
}
{
test: /\.css$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
}
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("css-loader!sass-loader")
}
]
},
plugins: [
new ExtractTextPlugin("src/components/assets/css/style.css", {
allChunks: true
})
]
};
module.exports = config;
There are two issues with this config.
The are no commas separating the loaders objects.
You are using ExtractTextPlugin but have not imported/required it anywhere in the config.
Issue #1 is quite obvious how to solve; simply add the commas after each definition of a loader object.
Issue #2 as well, you need to install and reference ExtractTextPlugin in you webpack config file.
You can do so by running the following command in your terminal:
npm install --save-dev extract-text-webpack-plugin
This will install the plugin to your node_modules and also list it in your package.json file under thedevDependencies` object.
And then in your webpack.config.js where you are requiring modules, also require the plugin like so:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
After making these changes, you config file should look something like this:
var path = require("path");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var config = {
entry: SRC_DIR + "/app/index.js",
output: {
path: DIST_DIR + "/app",
filename: "bundle.js",
publicPath: "/app/"
},
module: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["react", "es2015", "stage-2"]
}
},
{
test: /\.css$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("css-loader!sass-loader")
}
]
},
plugins: [
new ExtractTextPlugin("src/components/assets/css/style.css", {
allChunks: true
})
]
};
module.exports = config;

Related

Webpack not compiling scss to css

I'm building an app using webpack, babel, and Sass. Everything working fine but sass file not compiling css file even though it's not throwing any errors.
My Packages related to this are:
"webpack": "^3.10.0",
"css-loader": "^0.28.9",
"extract-text-webpack-plugin": "^3.0.2",
"glob-all": "^3.1.0",
"node-sass": "^4.7.2",
"purify-css": "^1.2.5",
"purifycss-webpack": "^0.7.0",
"sass-loader": "^6.0.6"
webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const glob = require('glob-all');
var PurifyCSSPlugin= require('purifycss-webpack');
module.exports = {
entry: './src/js/index.js',
output: {
path: __dirname,
filename: 'dist/js/bundle.js'
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'stage-3'],
}
}
},
{
test:/\.css$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {
url: false
}
}
]
})
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {
url: false
}
},
'sass-loader'
]
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: './dist/css/styles.css'
}),
new PurifyCSSPlugin({
paths: glob.sync([
path.join(__dirname, 'dist/index.html'),
path.join(__dirname, 'src/js/*.js')
])
})
]
}
Files Directory:
This is my project Files Directory
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: ['style-loader', 'css-loader', 'sass-loader']
options: {
url: false
}
},
]
})

How to compiling styles in webpack

I have this modules in package.json
{
"name": "v1.0",
"version": "1.0.0",
"description": "",
"main": "app-main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.1",
"node-sass": "^4.5.3",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.0",
"webpack": "^3.8.1"
},
"dependencies": {
"jquery": "^3.2.1"
}
}
`
My js bundle is working, but styles i cant compiling to 1 bundle for ex. main.bundle.css. This is my webpack.config.js
const path = require('path');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'app-main' : './assets/js/app-main.js',
'vendor-main': './assets/js/vendor-main.js'
},
output: {
path: path.resolve(__dirname, './js'),
filename: '[name].bundle.js'
},
module: {
rules: [{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
includePaths: ["css/scss/main.scss"]
}
}]
}],
loaders: [
{
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'css/[name].bundle.css',
allChunks: true,
}),
]
};
When i start webpack, i dont have any errors, my js bundle is working, but css not. How i can fix this problem?
You are missing the call to extract function in your loader rules:
const path = require('path');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'app-main': './assets/js/app-main.js',
'vendor-main': './assets/js/vendor-main.js'
},
output: {
path: path.resolve(__dirname, './js'),
filename: '[name].bundle.js'
},
module: {
rules: [{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
includePaths: ["css/scss/main.scss"]
}
}]
})
}],
loaders: [
{
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'css/[name].bundle.css',
allChunks: true,
}),
]
};
One more thing do not forget to require your .scss file in your .js file.

Uncaught Error: Expected 'styles' to be an array of strings

I have tried solutions proposed for this identical error message without success. When i run my angular project with the angular cli through ng serve, the project runs fine without errors. However, when i compile it with webpack, i get the (full) error message:
Uncaught Error: Expected 'styles' to be an array of strings.
at z (vendor.js:1)
at t.getNonNormalizedDirectiveMetadata (vendor.js:1)
at t.loadDirectiveMetadata (vendor.js:1)
at vendor.js:1
at Array.forEach (<anonymous>)
at vendor.js:1
at Array.forEach (<anonymous>)
at t._loadModules (vendor.js:1)
at t._compileModuleAndComponents (vendor.js:1)
at t.compileModuleAsync (vendor.js:1)
at e._bootstrapModuleWithZone (vendor.js:1)
at e.bootstrapModule (vendor.js:1)
at Object.<anonymous> (app.js:1)
at Object.199 (app.js:1)
at e (vendor.js:1)
at window.webpackJsonp (vendor.js:1)
at app.js:1
My webpack.config.js:
// Plugins
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
// Config
module.exports = {
entry: {
app: "./src/main.ts",
vendor: ["./src/vendor.ts", "./src/polyfills.ts"]
},
output: {
publicPath: "",
path: __dirname + "/dist/",
filename: "[name].js"
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
{
loader: "awesome-typescript-loader",
options: { tsconfig: "tsconfig.json" }
}, "angular2-template-loader"
]
},
{
test: /\.(html)$/,
loaders: [
{
loader: "html-loader"
}
]
},
{
test: /\.(css|scss)$/,
loaders: ['to-string-loader', 'css-loader', 'sass-loader']
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
comments: false
}),
new webpack.optimize.CommonsChunkPlugin({
names: ["app", "vendor"]
}),
new HtmlWebpackPlugin({
template: "src/index.tpl.html",
inject: "body",
filename: "index.html"
})
]
}
.angular-cli.json
{
"apps": [
{
"root": "src",
"outDir": "dist",
"index": "index.tpl.html",
"main": "main.ts",
"polyfills": "polyfills.ts"
}
],
"defaults": {
"styleExt": "css"
}
}
app-root / app.component.ts
import { Component } from "#angular/core";
import { Observable } from "rxjs/Rx";
import { NgFor } from "#angular/common";
#Component ({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
}
Any suggestions as to what i am doing wrong?
This was my webpack setup that worked for scss and css files. For this setup (using Angular Storybook, so this webpack config was located in ./storybook), I had a global stylesheet in app/styles that needed some extra massaging because it imported other stylesheets in that directory that used relative paths. I also had a custom stylesheet in the same directory as this webpack (./):
webpack.config.js
const path = require('path');
const autoprefixer = require('autoprefixer');
const postCSSCustomProperties = require('postcss-custom-properties');
const postcssPlugins = () => [
require('postcss-flexbugs-fixes'),
autoprefixer({ flexbox: 'no-2009' }),
postCSSCustomProperties({ warnings: true })
];
module.exports = (baseConfig, env, config) => {
baseConfig.module.rules = [
...baseConfig.module.rules.filter(r => !r.test.toString().includes(".s(c|a)ss")), // base rules supplied by Angular Storybook
...
{
test: /\.css$/,
use: [
'raw-loader',
{
loader: 'postcss-loader',
options: {
plugins: postcssPlugins
}
}
]
},
{ // component scss loader
test: /\.scss$/,
include: [path.resolve(__dirname, '../')],
exclude: [path.resolve(__dirname, '../app/styles'), path.resolve(__dirname, './')],
use: [
'raw-loader',
{
loader: 'postcss-loader',
options: {
plugins: postcssPlugins
}
},
'sass-loader'
]
},
{ // global and storybook scss loader
test: /\.scss$/,
include: [path.resolve(__dirname, '../app/styles'), path.resolve(__dirname, './')],
loaders: [
'style-loader',
'css-loader',
'resolve-url-loader', // resolves relative imports
'sass-loader?sourceMap' // sourcemap = true to assist resolve-url-loader
]
},
...
];
baseConfig.resolve.extensions.push(".css", ".scss");
baseConfig.resolve.alias = {
...baseConfig.resolve.alias,
"assets": path.resolve(__dirname, "../app/assets") // needed to resolve relative paths in imported scss using an alias, where the imported files referred to sheets like "url(~assets/path/to/pic.jpg)"
}
return baseConfig;
};
package.json
"dependencies": {
"#angular/core": "^6.1.3",
"resolve-url-loader": "^3.0.0",
},
"devDependencies": {
"#ngtools/webpack": "6.0.8",
"#storybook/angular": "^4.1.4",
"css-loader": "^0.28.11",
"postcss-custom-properties": "^7.0.0",
"postcss-flexbugs-fixes": "^3.3.1",
"postcss-loader": "^2.1.5",
"raw-loader": "^0.5.1",
"sass-loader": "^7.0.3",
"style-loader": "^0.23.1",
"webpack": "4.15.0"
}
I solved my issue, by following Shobhit's suggestion, adding the following to webpack.config.json:
...
rules: [
{
test: /\.(scss|css)$/,
use: ["raw-loader", "sass-loader"]
},
{
test: /\.scss$/,
exclude: [/node_modules/, /src\/app/],
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "sass-loader"]
})
}
...
And
plugins: [
new ExtractTextPlugin("styles.css")
...

Process less file to css with webpack in Asp.net core application

I am trying to process a less file with webpack to a css file, but it is not processed.
Here is where I say to webpack to process less files:
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var sharedConfig = {
resolve: { extensions: [ '', '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: '/dist/'
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: {
silent: true } },
{ test: /\.html$/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg|ttf|woff)$/, loader: 'url', query:
{ limit: 25000 } },
{ test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader",
"css-loader!less-loader")}
]
}
};
Here is the location of my less file:
Location less file
And in package.json I have the following:
"webpack": "^1.12.14",
"webpack-externals-plugin": "^1.0.0",
"webpack-hot-middleware": "^2.10.0",
"webpack-merge": "^0.14.1",
"zone.js": "^0.6.21",
"extract-text-plus-webpack-plugin": "^1.0.0",
"less-loader": "^4.0.3"

CSS file don't not create with webpack

I use webpack and i would like generate my CSS file with SASS.
So i've add css-loader and sass-loader. But, webpack don't create my CSS folder. My webpackconfig :
const webpack = require('webpack'),
ExtractTextPlugin = require('extract-text-webpack-plugin'),
BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: './js/app.js',
output: {
path: './public',
filename: 'app.bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-2']
}
},
{
test: /\.scss$/,
loaders: ExtractTextPlugin.extract(["style", "css", "sass"])
}
]
},
plugins: [
new ExtractTextPlugin('app.bundle.css'),
new BrowserSyncPlugin(
{
host: 'localhost',
port: 3000,
server: { baseDir: ['./'] }
}
)
]
}
Do you have any idea ?
Thank you !
You could use the style!css!sass loaders. Just install them using npm and set the config below in your webpack.config.
{
test: /\.scss$/,
loader: 'style!css!sass?sourceMap'
}
Your final webpack.config should look like this:
const webpack = require('webpack'),
ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './js/app.js',
output: {
path: './js',
filename: 'app.bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-2']
}
},
{
test: /\.scss$/,
loader: 'style!css!sass?sourceMap'
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
Now your CSS should be bundled properly.
plugins should be a root property, not a property of module.
const webpack = require('webpack'),
ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './js/app.js',
output: {
path: './js',
filename: 'app.bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-2']
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css!sass')
}
]
},
plugins: [
new ExtractTextPlugin('app.bundle.css')
]
}
You have to import the scss file somewhere, like your index.js or App.js:
e.g. import './sass/main.scss';

Resources