Webpack4: Process CSS and SCSS file with separate entry point - javascript

How can I target all CSS and SCSS files in a folder with an entry point, process them and then output the result into a single file in Webpack 4?
For JavaScript seems very straightforward: In the following example, I'm getting all files with js extension located in assets/js then they are transpiled and saved into /dist/bundle.js:
const path = require("path")
const glob = require("glob")
module.exports = {
devtool: 'source-map',
entry: glob.sync("./assets/js/*.js"),
output: {
path: path.resolve(__dirname, "./dist/js/"),
filename: 'bundle.js',
publicPath: '/dist'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: { presets: ["es2015"] }
}
}
]
},
}
I'd like to do the same (along with the previous example) but with CSS and SCSS files. I've tried:
const path = require("path")
const glob = require("glob")
const mcep = require("mini-css-extract-plugin")
module.exports = {
devtool: 'source-map',
entry: {
javascript: glob.sync("./assets/js/*.js"),
css: glob.sync("./assets/css/**/"),
},
output: {
path: path.resolve(__dirname, "./dist/js/"),
filename: 'bundle.js',
publicPath: '/dist'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: { presets: ["es2015"] }
}
},
{
test: /\.(sa|sc|c)css$/,
use: [
{
loader: mcep.loader
},
{
loader: "file-loader",
/*options: {
name: "bundle.css",
outputPath: "dist/css/"
}*/
},
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader" // translates CSS into CommonJS
},
{
loader: "sass-loader" // compiles Sass to CSS
}
]
}
]
},
plugins: [
new mcep({
filename: "./dist/css/[name].css",
chunks: ['css']
})
]
}
but it does not work. Again, I'd like to target all files within a specific folder, process them and ouput them into /dist/css/something.css, I don't want to import them into a js file.
Thanks

Related

Webpack exclusion with seperate entry points not working with file exclusion

I have a webpack config file(version 5.28.0) that I am trying to alter, in order to create two versions of the user.js file that is generated. I'd like a user.js and legacy_user.js file to be generated. Both files I would like to be generated from the contents of the 'scripts/user' directory, with the exception of I'd like the user.js file to compile excluding the legacy_user.js file that is in the 'scripts/user' directory and the legacy_user.js file to compile excluding the user.js file that is in the 'scripts/user' directory. I have tried the below but the contents of the user.js file keeps overwriting the contents of the legacy_user.js file and they end up being identical:
module.exports = (options = {}) => {
return [
{
mode: options.production ? 'production' : 'development',
entry: {
app: path.resolve(__dirname, 'scripts/app'),
user: path.resolve(__dirname, 'scripts/user'),
'video/trim': path.resolve(__dirname, 'scripts/video/trim')
},
output: { path: path.resolve(__dirname, '../public_html/dist') },
module: {
rules: [
{
test: /\.js$/,
exclude: [/(node_modules)/, /legacy_user\.js$/],
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['#babel/plugin-transform-runtime']
}
}
}, {
test: /\.(s[ac]ss|css)$/i,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{ test: /\.(png|jpg|woff(2)?|ttf|eot|svg)$/, loader: 'file-loader' }
]
},
},
{
mode: options.production ? 'production' : 'development',
entry: {
legacy_user: path.resolve(__dirname, 'scripts/user')
},
output: {
path: path.resolve(__dirname, '../public_html/dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/(node_modules)/, /user\.js$/],
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['#babel/plugin-transform-runtime']
}
}
}, {
test: /\.(s[ac]ss|css)$/i,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{ test: /\.(png|jpg|woff(2)?|ttf|eot|svg)$/, loader: 'file-loader' }
]
},
}
]
}
Any help on this would be greatly appreciated!

webpack 4 gives background: url([object Module]) as bg image

I'm having issues with setting up web-pack 4 and svg-sprite-loader to render svg icons as background images. I was following these instructions from official docs for svg-sprite-loader (https://github.com/kisenka/svg-sprite-loader/tree/master/examples/extract-mode).
I have successfully managed to create sprite.svg file in my dist folder and use it as reference for my use tags inside of html. However, i was also trying to use svg icons from my src/images/icons folder for a background image like this:
background: url('../images/icons/upload_icon.svg') 10% 50% no-repeat;
when doing this, webpack compiles correctly, but creates this in dist css file:
background: url([object Module]) 10% 50% no-repeat;
Any help would be great.
here is my webpack config file:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const SpriteLoaderPlugin = require("svg-sprite-loader/plugin");
module.exports = {
mode: "development",
devtool: "source-map",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
sourceMap: true
}
}
},
{
// scss configuration
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader"
},
{
loader: "postcss-loader"
},
{
loader: "sass-loader",
options: {
sourceMap: true
}
}
]
},
{
// html configuration
test: /\.html$/,
use: {
loader: "html-loader"
}
},
{
// images configuration
test: /\.(jpg|jpeg|gif|png|woff|woff2)$/,
use: [
{
loader: "file-loader",
options: {
name: "[path][name].[ext]"
}
}
]
},
{
test: /\.svg$/,
use: [
{
loader: "svg-sprite-loader",
options: {
extract: true,
spriteFilename: "sprite.svg"
}
}
]
}
]
},
plugins: [
// all plugins used for compiling by webpack
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Style Guide",
template: path.resolve(__dirname, "src", "index.html")
}),
new MiniCssExtractPlugin({
filename: "app.css"
}),
new SpriteLoaderPlugin()
]
};
Adding esModule: false to the file-loader options did the trick for me.
{
test: /\.(jpg|png|gif|svg)$/,
use: {
loader: 'file-loader',
options: {
name: "[name].[ext]",
outputPath: "img",
esModule: false
}
},
You have to pass esModule: false for svg-sprite-loader options.
By the way (it is not related to esModule): With MiniCssExtractPlugin you can not to extract svg sprite. I've faced this problem one hour ago..
After a few hours, I have managed to make this thing to work, thanks to #WimmDeveloper for pointing me in right direction. Main change from prior webpack config file is that I have added esModule: false in svg-sprite-loader options and replaced MiniCssExtractPlugin with extract-text-webpack-plugin. Mind you that this solution is not ideal since this webpack plugin is deprecated.
here is my full webpack config file:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const SpriteLoaderPlugin = require("svg-sprite-loader/plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
mode: "development",
devtool: "source-map",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
sourceMap: true
}
}
},
{
test: /\.(s*)css$/,
use: ExtractTextPlugin.extract({
use: ["css-loader", "postcss-loader", "sass-loader"]
})
},
{
// html configuration
test: /\.html$/,
use: {
loader: "html-loader"
}
},
{
test: /\.svg$/,
use: [
{
loader: "svg-sprite-loader",
options: {
esModule: false,
extract: true,
spriteFilename: "sprite.svg"
}
}
]
},
{
// files configuration
test: /\.(jpg|jpeg|gif|png|woff|woff2)$/,
use: [
{
loader: "file-loader",
options: {
name: "[path][name].[ext]"
}
}
]
}
]
},
plugins: [
// all plugins used for compiling by webpack
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Style Guide",
template: path.resolve(__dirname, "src", "index.html")
}),
new ExtractTextPlugin({ filename: "app.css" }),
new SpriteLoaderPlugin()
]
};

Webpack generates big file

Webpack generates too large a file
Webpack 2.x
Webpack experts, i now want to connect css in thejs file
How i include
import 'bootstrap/dist/css/bootstrap-theme.min.css';
import 'bootstrap-select/dist/css/bootstrap-select.min.css';
import 'bootstrap-multiselect/dist/css/bootstrap-multiselect.css';
import 'font-awesome/css/font-awesome.min.css';
import 'angular-ui-notification/dist/angular-ui-notification.min.css';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import '../css/styles.css';
import '../css/custom.css';
import '../css/max-width_767.css';
webpack config
var glob = require('glob'),
ngAnnotate = require('ng-annotate-webpack-plugin'),
ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: __dirname + '/application/application.js',
output: {
path: __dirname + '/build',
filename: 'bundle.js'
},
plugins: [
new ngAnnotate({
add: true,
}),
new ExtractTextPlugin({
filename: '[name].css',
})
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['babel-preset-es2015'].map(require.resolve)
},
exclude: /(node_modules|bower_components)/
},
{
test: /\.(png|woff|woff2|eot|ttf|svg|gif|jpg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
},
node: {
fs: 'empty'
}
};
That's what i'm getting out of the way, a huge bundle.js file is probably 5 MB with all fonts, pictures, etc.
bundle.js 5.53 MB 0 [emitted] [big] main
I just want to concatenate only css and output to bundle.css
What am I doing wrong ?
You have included extract-text-plugin but you dont actually seem to be using it.
Change here:
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
To something like:
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader"
})
}
it's answer
It was necessary to look at the limit
var glob = require('glob'),
ngAnnotate = require('ng-annotate-webpack-plugin'),
ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: __dirname + '/application/application.js',
output: {
path: __dirname + '/build',
filename: 'bundle.js'
},
plugins: [
new ngAnnotate({
add: true,
}),
new ExtractTextPlugin('bundle.css'),
],
resolve: {
alias: {
moment: __dirname + '/node_modules/moment/min/moment'
},
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['babel-preset-es2015'].map(require.resolve)
},
exclude: /(node_modules|bower_components)/
},
{
test: /\.(png|woff|woff2|eot|ttf|svg|gif|jpg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 1000
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}
]
},
node: {
fs: 'empty'
},
devServer: {
historyApiFallback: true
}
};

Vuejs / Webpack exclude json file from bundle

I have a no-sql database in the root of my project and I don't want webpack to include it in its bundle. Now I have to rebuild everytime the db gets updated. I'm using webpack 2.2.1. This is what I have:
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './resources/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
modules: [
resolve('resources'),
resolve('node_modules')
],
alias: {
'vue$': 'vue/dist/vue.common.js',
'src': resolve('resources'),
'assets': resolve('resources/assets'),
'components': resolve('resources/components')
}
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: "pre",
include: [resolve('resources'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('resources'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
I tried to exclude it by adding it to the externals like so
externals: ['./../db.json'],
Or adding a rule like so
{
test: /\.json$/,
exclude: resolve('db.json')
}
as long as you require()/import it, you will always have to re-build, because webpack will convert it into a new file, as a webpack module.
What you really have to do is load it via AJAX from the browser after your app has started, with your AJAX tool of choice.

Ignore specific #import in css files from webpack config

I have this webpack config
var Webpack = require("webpack");
var Path = require("path");
var OutputPath = "build";
module.exports = {
entry: "./src/app.tsx",
output: {
path: Path.join(__dirname, OutputPath, "" + process.env.NODE_ENV),
publicPath: "",
filename: "bundle.js"
},
devtool: "source-map",
devServer: {
contentBase: OutputPath
},
resolve: {
extensions: ["", ".ts", ".tsx", ".webpack.js", ".web.js", ".js", ".html"],
alias: {
jquery: "jquery/src/jquery"
}
},
node: {
fs: "empty"
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: "ts-loader" },
{ test: /\.html$/, loader: "html-loader!file-loader?name=[name].[ext]" },
{ test: /\.ejs$/, loader: "ejs-loader" },
{
test: /\.svg$/,
loaders: [
"url-loader?limit=100000&name=assets/[name].[hash].[ext]",
"image-webpack?bypassOnDebug=false&optimizationLevel=7&interlaced=false"
]
},
{
test: /\.(png|jpe?g|gif|woff|woff2|ttf|eot|ico)$/,
loader: "url-loader?limit=100000&name=assets/[name].[hash].[ext]"
},
,
{
test: /\.css$/,
exclude: /.*onsenui.*$/,
loader: "ignore-loader"
}
,
{
test: /\.(less|css)$/,
exclude: /.*(font_awesome|ionicons|iconic-font).*$/,
loader: "style-loader!css-loader?-import!less-loader!postcss-loader"
}
],
}
};
Application is built on onsenui and I am trying to ignore specific filename from css import.
#import url("font_awesome/css/font-awesome.min.css");
#import url("ionicons/css/ionicons.min.css");
#import url("material-design-iconic-font/css/material-design-iconic-font.min.css");
...
We can comment out the specific lines, but we don't want to do it every update npm packages.
Does anyone know, how to ignore that css imports?
Finally I just installed "string-replace-webpack-plugin" and use this way.
var StringReplacePlugin = require("string-replace-webpack-plugin");
Then adding that plugin into preloader does the work
preLoaders: [
{
test: /onsenui\.css$/,
loader: StringReplacePlugin.replace({
replacements: [
{
pattern: /.*(#import).*/ig,
replacement: function (match, p1, offset, string) {
return "/*/";
}
}
]}),
include: /node_modules\\onsenui.*/
}
]

Categories

Resources