Webpack sass-loader generating wrong / broken source maps - css

I'm trying to generate correct source maps for an large project (using monorepo, aliases for loading files from other sibling project, and bootstrap). Below is my webpack.config.js file. Currently, it generates hit or miss source map, sometimes it generates ok (for bootstrap files for instance, the map is perfect), sometimes it points to an completly diferent file and line from the original, and sometimes, it generates even an wrong scss file map. I've tried to enable compressed: true, but it just makes everything more messy, some files it point right but most of them to the wrong line or file.
the SCSS files are compiling as it should, but the source map is hit or miss. Is there something wrong with my configuration? Any simple boilerplate for generating correct sourcemaps?
{
mode: 'none',
name: 'scss',
entry: scssFiles, // list of entries generated by function
devtool: 'source-map',
stats: 'errors-warnings',
output: {
path: path.resolve(__dirname),
filename: '[name].css'
},
module: {
rules: [{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
url: false,
minimize: false
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
plugins: [
require('autoprefixer')()
]
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
// outputStyle: 'compressed', // Have tried it on too.
includePaths: [
path.resolve('node_modules'),
path.resolve('node_modules/flag-icon-css/sass')
]
}
}
]
})
}]
}

Related

Minimize SCSS to CSS with webpack keeping file/folder structure

I am having trouble understanding how to compile and minify my scss files to css, while keeping the same folder and file structure. I am using MiniCssExtractPlugin to extract everything, as well as style-loader, css-loader, postcss-loader, and sass-loader
Here is the file structure in my src folder
app.scss contains all the imports. importing from folders 1-7. I am first having trouble with the imports, and then have trouble compiling and minimizing the remaining scss files.
The end goal is to have an compiled folder look like this with each file being minimized and app.scss bundle all the imports
Here is a run down of the code I have so far for webpack.config.js
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css',
chunkFilename: '[id].css'
})
],
module: {
rules: [
{
test: /\.(scss|css)$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
]
}
]
},
optimization: {
minimizer: [new TerserJSPlugin({extractComments: false}), ],
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/](lodash)[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
When running this code, I just get an app.css file under a css folder that does not have imports included, and no other files are included as well. Can someone help my understand the process I need to take? I've been all over docs for each loader and not really understanding what I am looking for.
Thanks!

Configure fonts in webpack

I have a slight problem with webpack here; I'm somewhat unable to load fonts.
This is my webpack.config.js
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const devMode = true;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry:
[
'./src/main.js',
'./scss/main.scss'
],
output: {
filename: "main.min.js",
chunkFilename: '[name].bundle.min.js?bust=[chunkhash]',
path: path.resolve(__dirname, 'static_root'),
publicPath: "/assets/"
},
target: "node",
externals: [nodeExternals()],
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
ignoreOrder: false, // Enable to remove warnings about conflicting order
}),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].css',
outputPath: 'css/'
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../',
hmr: process.env.NODE_ENV == 'development',
}
},
],
},
{
test: /\.(woff2?|eot|ttf|otf|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '[name].[ext]'
}
}
]
}
};
This builds my css although then my local fonts aren't included / aren't rendered.. This also copies my Font to /static_root (which is where the css gets built to).
so I end up with this directory structure:
public/static_root/css/main.css
public/static_root/BebasNeue-Regular.ttf
public/static_root/main.min.js
I thought about just adjusting the path to the font in my scss file unfortunately though this lets the build process fail, since my working dir and the output root aren't the same.
My scss/font-directory is structured like so:
/public/scss/fonts/_fonts.scss
/public/scss/fonts/BebasNeueRegular.ttf
/public/scss/main.scss
So how can I achieve the inclusion of the font or how is this usually done since I found lots of different approaches online, that sadly didn't work out for me.
Any help would be greatly appreciated.
Greetings,
derelektrischemoench
So I found out what was causing the problems. It had to do something with the loader for the fonts (I was using an older one). I tried the whole thing with the url-loader like so:
{
test: /\.(woff2?|eot|ttf|otf|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '[name].[ext]'
}
}
... which got it going. It was just kinda confusing, since I found a bazillion of tutorials on the web on how to achieve this, of which the most part was deprecated.
Thanks for the responses.
hey #derelektrischemoench, I think the example in Webpack official website is pretty good, you could follow the webpack config and its file structure:
https://webpack.js.org/guides/asset-management/#loading-fonts

Webpack 4 - Style-loader/url not working

I'm having my webpack set up and it's running all fine, but in development it is serving my compiled scss stylesheets inline instead of using an URL.
module: {
rules: [
{
test: /\.scss$/,
use: [
{ loader: "style-loader"},
{ loader: "css-loader" },
{ loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}
},
{ loader: "sass-loader" }
]
}
]
}
So I grabbed the docs and read up on how to use a single CSS file instead. I updated my webpack config to the following and since all loaders are running in reverse order this should be working;
module: {
rules: [
{
test: /\.scss$/,
use: [
{ loader: "style-loader/url"},
{ loader: "file-loader" },
{ loader: "css-loader" },
{ loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}
},
{ loader: "sass-loader" }
]
}
]
}
It results in no errors, and inserts the following stylesheet into my header;
<link rel="stylesheet" type="text/css" href="6bbafb3b6c677b38556511efc7391506.scss">
As you can see it's creating an scss file, whereas I was expecting a .css file. I tried moving the file-loader around but that didn't work either and resulted in several crashes. Any idea how to turn this into a working css file?
I can't use mini-css-extract in my dev env since I'm using HMR. I already got this working on my prod env.
Update: When removing css-loader it compiles and shows my css applied to the page. But when I inspect the elements everything is on line 1 and the file it refers to can not be found
I'm importing my css like this in index.js by the way;
import '../css/styles.scss';
You can install extract-text-webpack-plugin for webpack 4 using:
npm i -D extract-text-webpack-plugin#next
The you can define the following constants:
// Configuring PostCSS loader
const postcssLoader = {
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
// Write future-proof CSS and forget old preprocessor specific syntax.
// It transforms CSS specs into more compatible CSS so you don’t need to wait for browser support.
require('postcss-preset-env')()
]
}
};
// Configuring CSS loader
const cssloader = {
loader: 'css-loader',
options: {
importLoaders: 1
}
};
Then in your SASS loader section, you can use the following:
ExtractTextPlugin.extract({
use: [cssloader, postcssLoader, 'sass-loader']
})
Then in you plugins section, you need to use the following:
new ExtractTextPlugin({
filename: 'css/[name].css'
)
Now suppose that your entry section is like below:
entry: {
app: 'index.js'
}
The generated CSS will be named as app.css and placed inside the css folder.
Another useful plugins for handling these type of post creating operations are:
HtmlWebpackPlugin and HtmlWebpackIncludeAssetsPlugin
Working with these plugins along with extract-text-webpack-plugin gives you a lot of flexibility.
I had a similar issue with webpack, after searching for a long time i found the soluton of combining a few plugins:
This is my result config: (as a bonus it preserves your sass sourcemaps;))
watch: true,
mode: 'development',
devtool: 'source-map',
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css", //make sure you use this format to prevent .scss extention in the hot reload file
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [
'css-hot-loader', //5. this will hot load all the extracted css.
MiniCssExtractPlugin.loader, //4 this will extract all css
{
loader: "css-loader", //3. this is where the fun starts
options: {
sourceMap: true
}
},
{
loader: "postcss-loader", //2. add post css
options: {
sourceMap: true
}
},
{
loader: "sass-loader", //1 . you can ingore the globImporter
options: {
importer: globImporter(),
includePaths: ["node_modules"],
sourceMap: true
}
}
]
},
]
}

Tilde in url with css modules does not work

Do you have some example config that works?
setting for webpack:
{
test: /\.scss$/,
use: ['style-loader', {
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]--[hash:base64:5]',
},
}, 'sass-loader'],
},
Usage:
background: url('~assets/arrow-white.svg') center no-repeat;
Output:
Module not found: Error: Can't resolve './assets/arrow-white.svg'
I can omit ~ or use ~/../assets and it works , but I would like to use it just ~.
Probably relevant bug: CSS modules break build if used with ~ https://github.com/webpack-contrib/css-loader/issues/589
I just copy your comment in order that you may close this question
the problem is that css-modules mode changes path resolution and
doesn't respect webpack module resolution
Use this package https://github.com/P0lip/url-tilde-loader
// In your webpack config
{
test: /\.s?css$/,
use: [
'style-loader',
{
loader: "css-loader",
options: {
modules: true,
},
},
{
loader: 'url-tilde-loader'
options: {
replacement: '~/../', // string to replace with
traverse: false, // use manual traversing
},
},
]
}

Webpack 1.15.0 FeathersJS React Redux Material-UI styles not compiled or present in rendered DOM

been having a tremendously difficult time determining why my stylesheets seem to be ignored in a package I am trying to modify for my own use. Not sure if this is a problem with Material-UI or Webpack itself, but any require or import statements I add to the head of any .js doc throw errors when running build script. The same imports for 'import style from './style.css' works in documents from original repository.
Best I am able to analyze the Webpack configs I am using seem to disregard any stylesheets except those a handful that were included with the original package AND any modifications within stylesheets that do render to the DOM are also disregarded. Everything I have researched indicates that this config works, and throws no errors when I run the corresponding build script.
Please help! Thank you!
webpack.production.configjs
/* eslint-env node */
/* eslint no-console: 0, no-var: 0 */
// Webpack config for PRODUCTION and DEVELOPMENT modes.
// Changes needed if used for devserver mode.
const webpack = require('webpack');
const rucksack = require('rucksack-css');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const envalid = require('envalid');
const path = require('path');
// Validate environment variables
validateEnvironmentVariables();
const config = require('config');
if (config.NODE_ENV === 'devserver') {
throw new Error('This webpack config does not work as is with the web-dev-server.')
}
const isProduction = config.isProduction;
const outputPublicPaths = {
production: '/dist/',
development: '/dist/',
devserver: 'http://localhost:8080/', // we don't use this config for webpack-dev-server
};
console.log(`----- ${config.NODE_ENV.toUpperCase()} build.`); // eslint-disable-line no-console
// Base Webpack configuration
const webpackConfig = {
context: path.join(__dirname, 'client'),
// re devtool: http://cheng.logdown.com/posts/2016/03/25/679045
devtool: isProduction ? 'cheap-module-source-map' : 'source-map',
entry: {
main: ['./index.js'],
// Webpack cannot produce chunks with a stable chunk hash as of June 2016,
// stable meaning the hash value changes only when the the code itself changes.
// See doc/FAQ.md#webpackChunks.
// This vendor chunk will not reduce network requests, it will likely force a second request
// each time the main chunk changes. So why separate them?
// Chunks for code which is dynamically optionally loaded makes sense.
// The first page will render faster as the parsing of such chunks can be delayed
// till they are needed.
// Of course the React routing must be changed to load such chunks as needed.
// Maybe we'll make the routing do that at some time.
/*
user: [
// './screens/Users/UserSignIn', // sign in occurs often enough to retain in main chunk
'./screens/Users/UserEmailChange',
'./screens/Users/UserForgotPwdReset',
'./screens/Users/UserForgotPwdSendEmail',
'./screens/Users/UserPasswordChange',
'./screens/Users/UserProfile',
'./screens/Users/UserProfileChange',
'./screens/Users/UserRolesChange',
'./screens/Users/UserSignIn',
'./screens/Users/UserSignInPending',
'./screens/Users/UserSignUp',
'./screens/Users/UserSignUpSendEmail',
'./screens/Users/UserSignUpValidateEmail',
],
*/
},
output: {
filename: '[name].bundle.[chunkhash].js',
// Tell Webpack where it should store the resulting code.
path: path.join(__dirname, 'public', 'dist'),
// Give Webpack the URL that points the server to output.path
publicPath: outputPublicPaths[config.NODE_ENV],
},
/* This is needed for joi to work on the browser, if the client has that dependency
node: {
net: 'empty',
tls: 'empty',
dns: 'empty',
},
*/
module: {
loaders: [
{
// File index.html is created by html-webpack-plugin. It should be a file webpack processes.
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
// When require'd, these /client/../*.inject.css files are injected into the DOM as is.
test: /\.inject\.css$/,
include: /client/,
loader: 'style!css',
},
{
// When required, the class names in these /client/../*.css are returned as an object.
// after being made unique. The css with the modified class names is injected into the DOM.
test: /^(?!.*\.inject\.css).*\.css$/,
include: /client/,
loaders: [
'style-loader',
'css-loader'
],
},
{
// Standard processing for .css outside /client
test: /\.css$/,
exclude: /client/,
loader: 'style!css',
},
{
test: /\.(js|jsx)$/, // does anyone still use .jsx?
exclude: /(node_modules|bower_components)/,
loaders: [
/*
'react-hot',
*/
'babel-loader',
],
},
{
test: /\.(svg|woff|woff2|ttf|eot)$/,
loader: 'file?name=assets/fonts/[name].[hash].[ext]'
},
],
},
resolve: {
extensions: ['', '.js', '.jsx'],
// Reroute import/require to specific files. 'react$' reroutes 'react' but not 'react/foo'.
alias: {
},
},
postcss: [
rucksack({
autoprefixer: true,
}),
],
plugins: [
// Webpack's default file watcher does not work with NFS file systems on VMs,
// definitely not with Oracle VM, and likely not with other VMs.
// OldWatchingPlugin is a slower alternative that works everywhere.
new webpack.OldWatchingPlugin(), // can use "webpack-dev-server --watch-poll" instead
/*
Build our HTML file.
*/
// repeat new HtmlWebpackPlugin() for additional HTML files
new HtmlWebpackPlugin({
// Template based on https://github.com/jaketrent/html-webpack-template/blob/master/index.ejs
template: path.join(process.cwd(), 'server', 'utils', 'index.ejs'),
filename: 'index.html',
inject: false, // important
minify: {
collapseWhitespace: true,
conservativeCollapse: true,
minifyCSS: true,
minifyJS: true,
preserveLineBreaks: true, // leave HTML readable
},
cache: false,
/* We'd need this if we had a dynamically loaded user chunk
excludeChunks: ['user'],
*/
// Substitution values
supportOldIE: false,
meta: { description: config.client.appName },
title: config.client.appName,
faviconFile: '/favicon.ico',
mobile: false,
links: [],
baseHref: null,
unsupportedBrowserSupport: false,
appMountId: 'root',
appMountIds: {},
addRobotoFont: true, // See //www.google.com/fonts#UsePlace:use/Collection:Roboto:400,300,500
copyWindowVars: {},
scripts: ['/socket.io/socket.io.js'],
devServer: false,
googleAnalytics: false,
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(config.NODE_ENV) }, // used by React, etc
__processEnvNODE_ENV__: JSON.stringify(config.NODE_ENV), // used by us
}),
],
};
// Production customization
if (isProduction) {
webpackConfig.plugins.push(
/*
Besides the normal benefits, this is needed to minify React, Redux and React-Router
for production if you choose not to use their run-time versions.
*/
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
comments: false,
sourceMap: false,
mangle: true,
minimize: true,
verbose: false,
})
);
}
module.exports = webpackConfig;
// Validate environment variables
function validateEnvironmentVariables() {
const strPropType = envalid.str;
// valid NODE_ENV values.
const nodeEnv = {
production: 'production',
prod: 'production',
development: 'development',
dev: 'development',
devserver: 'devserver',
testing: 'devserver',
test: 'devserver',
};
const cleanEnv = envalid.cleanEnv(process.env,
{
NODE_ENV: strPropType({
choices: Object.keys(nodeEnv),
default: 'developmwent',
desc: 'processing environment',
}),
}
);
process.env.NODE_ENV = nodeEnv[cleanEnv.NODE_ENV];
}
Just at a first glance, you need to add -loader to each loader. You've done it for one, but not the other two:
{
// When require'd, these /client/../*.inject.css files are injected into the DOM as is.
test: /\.inject\.css$/,
include: /client/,
loaders: [
'style-loader',
'css-loader'
]
},
{
// When required, the class names in these /client/../*.css are returned as an object.
// after being made unique. The css with the modified class names is injected into the DOM.
test: /^(?!.*\.inject\.css).*\.css$/,
include: /client/,
loaders: [
'style-loader',
'css-loader'
],
},
{
// Standard processing for .css outside /client
test: /\.css$/,
exclude: /client/,
loaders: [
'style-loader',
'css-loader'
]
},

Resources