Combining SCSS and CSS Into A Single File With WebPack - javascript

I'm a newbie to webpack and I'm having trouble understanding how I can take a bunch of scss files and css files and merge them together with webpack (After transpiling the sass of course).
With gulp, it was really obvious, as I can have 1 step the transpile the sass to css and then a step after that to concatenate them together.
However with webpack, it looks like everything happens at the same time.
This is a pretty basic requirement that I'm sure has an obvious answer to those more experienced.
I've got to the point where I can successfully output a transpiled scss to css and seperately output a css file from css input, but I can't figure out how to stick them together using webpack.
Below is my webpack.config.js file:
const path = require('path');
const webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('extractedCSS.css');
const extractSass = new ExtractTextPlugin({
filename: "extractedSASS.css",
disable: process.env.NODE_ENV === "development"
});
module.exports = function (env) {
return {
context: path.resolve(__dirname, './wwwroot/app'),
entry: {
main: './index.js',
vendor: 'moment'
},
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, './wwwroot/mytempdist')
},
module: {
rules: [{
test: /\.css$/,
use: extractCSS.extract({
use: 'css-loader'
})
},
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
// use style-loader in development
fallback: "style-loader"
})
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
//CommonChunksPlugin will now extract all the common modules from vendor and main bundles
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest' //But since there are no more common modules between them we end up with just the runtime code included in the manifest file
}),
//new webpack.optimize.UglifyJsPlugin({
// sourceMap: options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)
//}),
extractSass,
extractCSS
],
devtool: 'inline-source-map'
}
}
How can I modify the above to make both the sass and css go into the file css output file?
Incase it makes a difference, below is an exerpt from my index.js file (entry point) toastr is an npm package and pace is just a normal downloaded css file:
var toastr = require('toastr');
import 'toastr/toastr.scss';
import pace from './../lib/pace/pace.min.js';
import './../lib/pace/pace.css';

You have 2 instances of ExtractTextPlugin defined with explicit names and you use those separate instances to load css and scss files respectively.
What you need is only 1 instance of the plugin which will accumulate all the CSS and only one rule for both scss and css files.
{
test: /\.s?css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
This will handle both scss and css files and put it all in one single output CSS file.

Related

How to bundle JS and CSS file independently with Webpack?

I have a few JS and SCSS files. I need Webpack 4 to bundle each JS entry to one JS file and each SCSS entry to one CSS file. The JS files don't import the SCSS files. I try to do it with the following webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: {
scriptFoo: './src/js/scriptFoo.js',
scriptBar: './src/js/scriptBar.js',
// ...
styleBaz: './src/css/styleBaz.scss',
styleBaq: './src/css/styleBaq.scss'
// ...
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.(scss|sass)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css'
})
]
};
It works fine, Webpack puts the compiled files to the dist directory. But it also creates an excess dummy JS file for each SCSS file in the dist directory:
webpack.config.js
src/
js/
scriptFoo.js
scriptBar.js
...
css/
styleBaz.scss
styleBaq.scss
...
dist/
scriptFoo.js
scriptBar.js
...
styleBaz.css
styleBaz.js // Excess
styleBaq.css
styleBaq.js // Excess
...
How to make Webpack not to create the excess JS files?
Use the ignore-emit-webpack-plugin Webpack plugin to not create the excess file. First install it by running in a console:
npm install --save-dev ignore-emit-webpack-plugin
Then add it to your Webpack configuration:
const IgnoreEmitPlugin = require('ignore-emit-webpack-plugin');
module.exports = {
// ...
plugins: [
// ...
new IgnoreEmitPlugin(['styleBaz.js', 'styleBaq.js']) // Or simply: new IgnoreEmitPlugin(/^style.*\.js$/)
]
};
It is because for each property in the entry object ,The js file is created in output destinations.
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
Webpack creating dummy js when css is an entry point is a known bug, which has not been fixed yet.
Also having multiple entry files in the entry configuration will also affect treeshaking capabilties

Is there a way to build scss files into css with webpack 4

I'm just trying out Webpack 4 and I was wondering if it had a built-in way to manage Scss files since ExtractTextPlugin doesn't work.
In Webpack 4 you also need to use extract-text-webpack-plugin in order to extract text from bundles. The problem is that stable version isn't compatible with the new plugin system. The team is working on it, but in the meantime you need to install the v4.0.0-beta.0 version.
yarn add extract-text-webpack-plugin#next --dev
You can also check this webpack-demo on GitHub with more configs.
The use on webpack.config.js script remains the same:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
// ...
module: {
rules: [
{
test: /.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
modules: true,
camelCase: 'dashes',
minimize: true
}
},
{
loader: 'sass-loader'
}
]
})
}
]
},
plugins: [
new ExtractTextPlugin('[name].[chunkhash].css')
]
}

Extracting sass as css using webpack

First. I know questions like this were asked, but I am missing something to understand them. I am trying to compile scss to css. And I would like webpack to basically do the same as sass app.scss : app.css. I tried to configure it using extract-text-webpack-plugin, but I am doing something wrong or missing smth.
It worked if I include(app.scss) in app.js but this makes no sense because if anyone has disabled JavaScript the styles won't work.
This is my webpack.config.js file. I have no idea how to do it.
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var jsConfig = {
entry: "./_dev/scripts/app.js",
output: { filename: "./scripts/bundle.js" },
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
}
};
var scssConfig = {
entry: "./_dev/scss/app.scss",
output: { filename: "./content/app.css" },
module: {
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new ExtractTextPlugin({filename:"./_dev/scss/app.scss"}),
]
};
var config = [scssConfig, jsConfig];
module.exports = config;
Edit: I also found this. This series would have helped with all my questions so if you have similar questions make sure to read it before asking!
https://codeburst.io/simple-beginner-guide-for-webpack-2-0-from-scratch-part-v-495dba627718
You need to include your app.scss for webpack to be able to find your scss references because webpack will traverse your project and apply loaders to all files it can find through references starting from app.js recursively down. If you don't have references to app.scss somewhere in the project webpack can't find it and it won't build it. So in the entry of you project (assume it is app.js) you need to do this:
import 'relative/path/to/styles/app.scss';
But it doesn't mean that those who don't have js enabled won't receive your styles. You need to include app.scss only for the build phase of your project, after that your styles will be included in html and will be loaded even for those without js enabled.
webpack concepts section explains how webpack finds dependencies based on your entry point building its internal graph of dependencies.
Update:
There is a way that allows you to not add your app.scss in your js. You can include multiple files in your entry object in your webpack config. Here is an example of how configuration might look in your case:
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var config = {
entry: {
main: [
"./_dev/scripts/app.js",
"./_dev/scss/app.scss"
],
},
output: {
path: './scripts',
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.(css|scss)/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin("./_dev/scss/app.scss"),
]
};
module.exports = config;
More information available on SO question webpack-multiple-entry-points-sass-and-js.
You also have incorrect configuration of ExtractTextPlugin in webpack. You are placing the whole path in the option for filename, which is not correct. In your case it should look like this:
plugins: [
new ExtractTextPlugin("./_dev/scss/app.css"),
]

webpack - compile every scss to css file with same name

I'd like to have structure like this
-Styles
--Main.scss
--SomeComponent.scss
-CompiledStyles
--Main.css
--SomeComponent.css
Actually I can only do this
-Styles
--Main.scss
--SomeComponent.scss
--All.scss (import all scss from file)
-CompiledStyles
--Main.css ( all css)
This is my webpack config
var Path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS2 = new ExtractTextPlugin('[name].css');
module.exports = {
devtool: 'eval',
entry: './Client/Styles/All.scss',
output: {
path: Path.join(__dirname, 'CompiledStyles'),
filename: 'page.js',
publicPath: '/CompiledStyles/'
},
module: {
loaders: [
{
test: /\.scss$/,
loader: extractCSS2.extract("style-loader", "css-loader!autoprefixer-loader!sass-loader")
},
{
//IMAGE LOADER
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader'
},
{
test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]'
}
]
},
plugins: [
extractCSS2
]
};
Is it possible to compile this scss files to single css files ?
I really don't know how to manage this case. I've tried to assign entry: './Client/Styles' but it occures error.
EDIT:
I solved this with gulp.
The idea of webpack is to put everything that is needed in some JavaScript-files. So it's the intention to not build a css-file for every css-file.
If you want to still use webpack, try this in your webpack config:
module.exports = {
// ...
entry: {
'Main': './Client/Styles/Main.scss',
'SomeComponents': './Client/Styles/SomeComponents.scss',
},
// ...
}
I have updated the answer after adamo94 noted that he used gulp, so just for everybody else some more information. To convert scss files you need a sass/scss-processor. You can easily call that processor with a single call but as you usually do more with your sources it's likely to use some further processing.
Usually you would use gulp or grunt. Those can be configured to build everything that you need. They have different pros and cons, there are also further tools, but those are probably the ones that you'd like to take a look.

Webpack how to use to merge css files?

I use Webpack to merge javascript files. But i do not understand how merge css files like javascript
var webpack=require('webpack');
module.exports = {
context: __dirname ,
entry: {one:["./script/born.js","./script/create_game.js"], two:["./css/destop.css", "./css/main_page.css"]},
output: {
path: __dirname,
filename: "/production/[name].js"
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
Is it possible to do such a thing?
To move every require("style.css") in entry chunks into a separate CSS file. And do not inline css into the JS bundle, but separate it in a CSS bundle file (styles.css). Use extract-text-webpack-plugin. There is an example from its documentation:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader"
})
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
}
If you need to merge json data or some another data that may be converted to json by loaders chain use merge-webpack-plugin. If you need to join togather some more specific things use join-webpack-plugin.

Categories