My SASS variables into :root are not interpolated - css

I'm fairly new to the Nuxt ecosystem. Awesome package that makes our lives much easier.
I'm trying to add sass to my project. After following the documentation my build runs perfectly but my scss files are not being compiled. An example of the problem:
Notice that --thm-font is set to $primaryTypography and not the actual value from the .scss.
I'm expecting to see --thm-font: 'Barlow', sans-serif. I'm assuming that the sass is not being compiled. It is important to note I'm not looking for a component base style but I'm trying to have a main.scss where I will import the component, layouts and many other styles.
_variables.scss
// Base colors
$base: #ee464b;
$baseRgb: (238, 70, 75);
$black: #272839;
$blackRgb: (39, 40, 57);
$grey: #f4f4f8;
// Typography
$primaryTypography: 'Barlow', sans-serif;
#debug $primaryTypography; // -> this one outputs the correct value
:root {
--thm-font: $primaryTypography;
--thm-base: $base;
--thm-base-rgb: $baseRgb;
--thm-black: $black;
--thm-black-rgb: $blackRgb;
--thm-gray: $grey;
}
nuxt.config.js
export default {
mode: 'universal',
loading: { color: '#fff' },
css: [
'~assets/scss/main.scss'
],
plugins: [
],
buildModules: [
],
modules: [
],
optimizedImages: {
optimizeImages: true
},
build: {
extend (config, ctx) {
},
loaders: {
sass: {
prependData: '#import "~#/assets/scss/main.scss";'
}
}
},
server: {
port: process.env.APP_PORT
}
}
package.json
{
"name": "zimed",
"version": "1.1.0",
"description": "Zimed - Vue Nuxt App Landing Page Template",
"author": "Layerdrops",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"dependencies": {
"#bazzite/nuxt-optimized-images": "^0.3.0",
"nuxt": "^2.0.0",
"sass-loader": "10"
},
"devDependencies": {
"fibers": "^5.0.0",
"sass": "^1.38.2"
}
}
Which configuration am I missing so that .scss files get compiled?

You need to interpolate the variable like this --thm-font: #{$primaryTypography}; in the scope of :root.
Not sure the why of this behavior, but this answer was my way of finding this out.

Related

How to (successfully) bundle css for dynamic multi-page app using Webpack 5

I am trying to use Webpack 5 to bundle assets for a dynamic multi-page Django application. Using WebpackManifestPlugin and django-manifest-loader. I have this working fine for JavaScript, but I've tried every tip I can find and have not been able to make it work for css.
I have created a css file to use as an entry point and (for proof of concept) imported 1 of the application's css files into that. The output file that is produced from that is effectively empty. If I add any rules directly to the entry .css file, then those rules show up in the output file, but the #import … is gone and the rules from the imported file are not present.
Incidentally, if I purposefully mis-name the file in the import, then bundling fails, so I think the imported css is being correctly recognized and processed, then omitted. Based on some of the reading I have done, I added sideEffects: true (see django/webpack.config.js contents below) but that did not change the results.
Any advice? I've been tearing my hair out for almost 2 days on this.
django/ui/src/index.css
#import 'css/components/navigation/notifications.css';
Resulting django/dist/main.512f6e37f2c08258132d.css
/*!******************************************************************************************************!*\
!*** css ./node_modules/css-loader/dist/cjs.js!./ui/src/css/components/navigation/notifications.css ***!
\******************************************************************************************************/
/*!***********************************************************************************************************!*\
!*** css ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./ui/src/index.css ***!
\***********************************************************************************************************/
Here's what I have in my django/webpack.config.js file:
/*global __dirname, module, require*/
const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const {WebpackManifestPlugin} = require('webpack-manifest-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
main: ['./ui/src/index.js', './ui/src/index.css'],
},
devtool: 'inline-source-map',
plugins: [
// Remove outdated assets from the output dir
new CleanWebpackPlugin(),
// Generate the required manifest.json file
new WebpackManifestPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
}),
],
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
sideEffects: true,
},
{
test: require.resolve('vue'),
loader: 'expose-loader',
options: {
exposes: ['Vue'],
},
},
],
},
output: {
// Rename files from example.js to example.8f77someHash8adfa.js
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
// https://webpack.js.org/migrate/5/
// > * 404 errors pointing to URLs containing auto
// > - Not all ecosystem tooling is ready for the new default
// > automatic publicPath via output.publicPath: "auto"
// > - Use a static output.publicPath: "" instead.
publicPath: '',
},
resolve: {
alias: {
// If using the runtime only build
vue$: 'vue/dist/vue.runtime.esm.js', // 'vue/dist/vue.runtime.common.js' for webpack 1
// Or if using full build of Vue (runtime + compiler)
// vue$: 'vue/dist/vue.esm.js' // 'vue/dist/vue.common.js' for webpack 1
},
},
};
In case it's helpful, here's what is in my django/package.json:
{
"name": "hub-ui",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack --watch --mode=development",
"build": "webpack --mode=production",
"dev": "webpack --mode=development"
},
"keywords": [],
"author": "Cliosoft",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^6.3.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^7.18.0",
"expose-loader": "^3.0.0",
"mini-css-extract-plugin": "^2.3.0",
"node-sass": "^6.0.1",
"sass-loader": "^12.1.0",
"style-loader": "^3.2.1",
"webpack": "^5.0.0",
"webpack-cli": "^4.8.0",
"webpack-manifest-plugin": "^4.0.2"
},
"dependencies": {
"bootstrap": "^5.1.1",
"bootstrap-vue": "^2.21.2",
"vue": "^2.6.14"
},
"engines": {
"node": "~16.9",
"npm": "~7.23"
}
}
This turned out to be a "did you turn it on?" kind of problem.
The css file I was using as the test case was supposedly a copy of a css file from its previous location, but it was actually an empty file of the same name. Doh!
Once I actually copied the styles into the .css file, everything started to work correctly.
Hopefully, this will be of some help to someone in the future. If you spend many days trying to figure out what's wrong with your package.json, webpack.config.js, etc. and can't find anything wrong with them, then maybe the problem is somewhere else like not having the content in your source files that you think you have.

Tailwind css does not reduce file size after purge

i have a basic html file (index.html), my project structure is like below :
index.html
tailwind.config.js
postcss.js
tailwind.css
dist.css
and here contents for each files
module.exports = {
purge: {
enabled:true,
content:['./*.html', './**/*.html'],
layers: ['components']
},
theme: {
extend: {
fontSize:{
'small' : '.6rem',
// Or with a default line-height as well
'3xl': ['2.5rem', {
lineHeight: '50px',
}],
'6xl': ['3.70rem', {
lineHeight: '60px',
}],
},
colors:{
transparent: 'transparent',
current: 'currentColor',
orange:{
DEFAULT: '#F47521'
}
},
screens: {
'sm': '640px',
'md': '760px',
'custom' : '980px',
'lg': '1024px',
'xl': '1280px',
'2xl': '1536px',
'3xl': '1600px',
'xxl' : '1700px'
}
}
},
variants: {
textColor: ['responsive', 'hover', 'focus', 'visited'],
},
plugins: [
({addUtilities}) => {
const utils = {
'.translate-x-half': {
transform: 'translateX(50%)',
},
};
addUtilities(utils, ['responsive'])
}
]
};
the postcss file
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}
and my package.json
{
"name": "myproject",
"version": "1.0.0",
"description": "my theme",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "NODE_ENV=production npx tailwindcss-cli#latest build tailwind.css -o dist.css",
"build:css": "postcss tailwind.css -o dist.css"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^10.2.5",
"postcss": "^8.2.8",
"tailwindcss": "^2.0.4"
},
"dependencies": {
"cssnano": "^4.1.10",
"postcss-cli": "^8.3.1"
}
}
when building with : npm run build, tailwind build the project but the dist.css size remains 5,7MB
What i'm doing wrong here?
thank you
You have purge configured to apply to the 'components' layer.
Tailwind has three layers: 'base', 'components', and 'utilities'. Components is the smallest of the three so its impact on the resulting filesize will be fairly minimal. You're hitting 5.7MB because by far the largest layer, 'utilities', is being ignored.
Update your purge configuration to apply to utilities too. Unless there's a good reason to be selective with layers, you probably want to drop any specificity and allow it to apply to all layers.
Furthermore, if you leave out enabled, it will be handled automatically based on your NODE_ENV setting.
https://tailwindcss.com/docs/optimizing-for-production#purging-specific-layers

How to fix broken CSS on Netlify when using Gatsby?

I'm not sure where to begin troubleshooting a gatsby/netlify issue. When I run gatsby develop locally, my site looks one way, when I deploy to Netlify, it works another.
Where does one even begin fixing/troubleshooting this sort of thing?
My gatsby-config.js
const dotenv = require("dotenv")
dotenv.config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `Berlin Music Map`,
description: "Find live music in Berlin",
author: `Kyle Pennell`,
},
plugins: [
'gatsby-plugin-sharp',
'gatsby-transformer-sharp',
`gatsby-plugin-react-helmet`,
// {
// resolve: "gatsby-plugin-remote-images",
// options: {
// nodeType: "item",
// imagePath: "thumbnail",
// name: 'optimized_thumbnail',
// }
// },
{
resolve: "gatsby-plugin-remote-images",
options: {
nodeType: "item",
imagePath: "soundcloud_artwork",
name: 'optimized_soundcloud_artwork',
}
},
{
// keep as first gatsby-source-filesystem plugin for gatsby image support
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/static/img`,
name: 'uploads',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/pages`,
name: 'pages',
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
},
},
{
resolve: `gatsby-plugin-material-ui`,
options: {
theme: {
palette: {
primary: {
lighter: '#47B3C0',
light: '#397AB2',
main: '#005691',
dark: '#202E5F',
},
secondary: {
lighter: '#FFECC4',
light: '#FED969',
main: '#E7A700',
dark: '#C45527',
},
},
typography: {
html:{
fontSize:"14px"
},
h1: {
fontSize: "3.052em"
},
h2: {fontSize: "2.441em"},
h3: {fontSize: "1.953em"},
h4: {fontSize: "1.563em"},
h5: {fontSize: "1.25em"},
h6: {fontSize: "1.05em"},
fontFamily: '"Raleway", "Open Sans", "Arial", sans-serif',
useNextVariants: true,
},
},
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// 'gatsby-plugin-offline',
],
}
package.json
{
"name": "gatsby-starter-default",
"private": true,
"description": "A simple starter to get up and developing quickly with Gatsby",
"version": "0.1.0",
"author": "Kyle Mathews <mathews.kyle#gmail.com>",
"dependencies": {
"#material-ui/core": "^4.5.1",
"#material-ui/icons": "^4.5.1",
"#tippy.js/react": "^3.0.1",
"axios": "^0.19.0",
"dotenv": "^8.0.0",
"gatsby": "^2.17.7",
"gatsby-cli": "^2.8.8",
"gatsby-image": "^2.2.29",
"gatsby-plugin-layout": "^1.1.13",
"gatsby-plugin-manifest": "^2.2.25",
"gatsby-plugin-material-ui": "^2.1.6",
"gatsby-plugin-offline": "^2.0.25",
"gatsby-plugin-react-helmet": "^3.0.10",
"gatsby-plugin-remote-images": "^1.0.7",
"gatsby-plugin-sharp": "^2.2.32",
"gatsby-remark-copy-linked-files": "^2.0.11",
"gatsby-remark-images": "^3.0.1",
"gatsby-remark-relative-images": "^0.2.1",
"gatsby-source-filesystem": "^2.1.35",
"gatsby-transformer-remark": "^2.3.4",
"gatsby-transformer-sharp": "^2.1.9",
"google-map-react": "^1.1.5",
"lodash": "^4.17.15",
"memoize-one": "^4.0.2",
"moment": "^2.24.0",
"prop-types": "^15.7.2",
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-fa": "^5.0.0",
"react-helmet": "^5.2.0",
"react-player": "^1.11.1",
"react-soundcloud-player": "^1.1.1",
"react-virtualized-auto-sizer": "^1.0.2",
"react-window": "^1.2.2",
"tippy.js": "^5.0.1"
},
"devDependencies": {
"prettier": "^1.16.4"
},
"keywords": [
"gatsby"
],
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write src/**/*.{js,jsx}",
"start": "npm run develop",
"serve": "gatsby serve",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
},
"repository": {
"type": "git",
"url": "https://github.com/gatsbyjs/gatsby-starter-default"
},
"bugs": {
"url": "https://github.com/gatsbyjs/gatsby/issues"
}
}
https://codesandbox.io/s/github/kpennell/berlinmusicmap/tree/master/?fontsize=14
The CSS injection order when doing gatsby build is a place to start. Material UI styles can get messed up when they are not injected first.
How to do it in the gatsby plugin:
https://www.gatsbyjs.org/packages/gatsby-plugin-material-ui/#advanced
From the MUI docs: https://material-ui.com/styles/advanced/#css-injection-order
Can you try to run gatsby build && gatsby serve on your local machine? Then go to localhost:9000 to see if your layout is all messed up.
Generally, it's good to check the built version of your Gatsby site by running this command. Especially since the new build time pricing of Netlify 😱
The issue might be independent of Netlify and related to Material UI.
Check this issue: https://github.com/mui-org/material-ui/issues/18197 you might find some useful information in it.
I (seemingly) solved this by literally copying what I had gatsby-browser.js to gatsby-ssr.js (wrapRootElement + wrapPageElement). I'm still not totally sure why this worked -- I'll need to read more about these in Gatsby's docs.
Dear frustrated/lost person from the future seeing wacky different CSS between gatsby develop and gatsby build ....if you're using React Context, try verbatim copying your wrapRootElement/wrapPageElement between the two files.

Failing to load background-image with sass-loader (Webpack)

I'm having trouble trying to get the browser to successfully find a background image whilst using webpack and sass-loader/style-loader/css-loader.
The path seems to be right, because whenever I change it the compile process fails, but as it is, it is ok.
So far I have...
Component
import React from 'react'
const Image = () => (
<div className='sprite-container sprite-1'>
</div>
)
export default Image
CSS
.sprite-container {
width: 100px;
height: 100px;
border-radius: 100%;
border: 1px solid blue; // I put this just to confirm the container div is there, which it is.
background-image: url('/img/spritesheet.png');
background-repeat: no-repeat;
position: absolute;
top: 250px;
right: 20px;
}
.sprite-1 {
background-position: -100px, -100px;
}
As it is, the div is transparent. The container is there but the background image fails to load. I'm new to compiling SASS in Webpack, so maybe this is something to do with my file structure.
This is the relevant part of my file tree:
- src
- static (all static assets are served from this folder)
- img
-- spritesheet.png
- styles
-- app.scss
-- app-client.js (importing app.scss here)
I'm importing the app.scss into my main js file, app-client.js (which React mounts to the application).
Does the path given in the background-image css property need to be relative the root directory or the stylesheet? I'm assuming the root directory (/static).
Any help appreciated.
UPDATE
File tree
- src
- static (all static assets are served from this folder)
- img
-- spritesheet.png
- js
-- bundle.js
- styles
-- app.scss
-- app-client.js (importing app.scss here)
webpack.config.js
const debug = process.env.NODE_ENV !== "production";
const webpack = require('webpack');
const path = require('path');
// const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
devtool: debug ? 'inline-sourcemap' : null,
entry: path.join(__dirname, 'src', 'app-client.js'),
devServer: {
inline: true,
port: 3333,
contentBase: "src/static/",
historyApiFallback: {
index: '/index-static.html'
}
},
output: {
path: path.join(__dirname, 'src', 'static', 'js'),
publicPath: "/js/",
filename: 'bundle.js'
},
module: {
loaders: [
{
test: path.join(__dirname, 'src'),
loader: ['babel-loader'],
query: {
cacheDirectory: 'babel_cache',
presets: debug ? ['react', 'es2015', 'react-hmre'] : ['react', 'es2015']
}
},
{
test: /\.scss$/,
loaders: [ 'style', 'css?sourceMap', 'sass?sourceMap' ]
// loader: ExtractTextPlugin.extract(
// 'style', // The backup style loader
// 'css?sourceMap!sass?sourceMap'
// )
},
{
test: /\.png$/,
loader: "url-loader?limit=10000&minetype=image/jpg"
}
]
},
plugins: debug ? [] : [
// new ExtractTextPlugin('styles.css'),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
mangle: true,
sourcemap: false,
beautify: false,
dead_code: true
}),
]
};
package.json
{
"name": "***",
"version": "1.0.0",
"description": "***",
"main": "src/server.js",
"repository": "**REPO**",
"scripts": {
"start": "NODE_ENV=production node_modules/.bin/babel-node --presets 'react,es2015' src/server.js",
"start-dev": "npm run start-dev-hmr",
"start-dev-single-page": "node_modules/.bin/http-server src/static",
"start-dev-hmr": "node_modules/.bin/webpack-dev-server --progress --inline --hot",
"build": "NODE_ENV=production node_modules/.bin/webpack -p"
},
"author": "***",
"license": "UNLICENSED",
"dependencies": {
"axios": "^0.15.3",
"babel-cli": "^6.11.4",
"babel-core": "^6.13.2",
"babel-loader": "^6.2.5",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-object-rest-spread": "^6.22.0",
"babel-preset-es2015": "^6.13.2",
"babel-preset-react": "^6.11.1",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-2": "^6.22.0",
"ejs": "^2.5.1",
"express": "^4.14.0",
"react": "^15.3.1",
"react-dom": "^15.3.1",
"react-redux": "^5.0.2",
"react-router": "^2.6.1",
"redux": "^3.6.0",
"redux-logger": "^2.7.4",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"css-loader": "^0.26.1",
"file-loader": "^0.9.0",
"http-server": "^0.9.0",
"node-sass": "^4.3.0",
"react-hot-loader": "^1.3.0",
"sass-loader": "^4.1.1",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.14.1"
}
}
I ran into the same problem. I found that you can include ?url=false in your css-loader to disable url handling. Then you can just place an image in your public folder for css to access. The image won't be run through webpack, but it will get you past webpack's compile errors and still allow images to be accessed.
So here is my new object in the module.loaders array:
{
test: /\.s?css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader?url=false', 'sass-loader']
})
}
Ok, I found the answer on another stack overflow question: Webpack - background images not loading
It turns out it was a bug, caused by the sourceMap of css-loader.
I changed this...
{
test: /\.scss$/,
loaders: [ 'style', 'css?sourceMap', 'sass?sourceMap' ]
}
...to this:
{
test: /\.scss$/,
loaders: [ 'style', 'css', 'sass?sourceMap' ]
}
Hope that helps anyone else who faces this problem as it wasted a good few hours for me!

How do I add global styles without requiring an extra component?

I want to apply some global styles to my website (body, h1, h2, h3, etc).
To do this with Angular2, the view encapsultation of a component needs to be set thusly: encapsulation: ViewEncapsulation.None.
example:
#Component({
selector: 'app-root',
templateUrl: template(),
styleUrls: ['global.scss', 'app.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class AppComponent {
title = 'Hello world!';
}
The problem is that this encapsulation rule applies to all of this components stylesheets, which means I must have a separate component just for global styles.
Is there another way to do this without requiring an extra component and without needing to edit Angular-CLI's build config?
(I'm using angular/core 2.0.0-rc.5 and angular-cli 1.0.0-beta.11-webpack.2)
The PR mentioned by drbishop has been merged and released as 1.0.0-beta.11-webpack.3.
To upgrade from 1.0.0-beta.11-webpack.2 to 1.0.0-beta.11-webpack.3, run:
npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli#1.0.0-beta.11-webpack.3
Note: if you get SyntaxError: Unexpected token ... errors on running ng version after upgrading you may need to upgrade to Node.js 6. See https://github.com/angular/angular-cli/issues/1883 for details.
If you generate a new project using 1.0.0-beta.11-webpack.3, you can add a styles.css file to your src directory which will be automatically included in your build. You can also add external CSS imports to the apps[0].styles property of angular-cli.json.
Your angular-cli.json should look something like this for a new project generated by 1.0.0-beta.11-webpack.3:
{
"project": {
"version": "1.0.0-beta.11-webpack.3",
"name": "demo"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": "assets",
"index": "index.html",
"main": "main.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"prefix": "app",
"mobile": false,
"styles": [
"styles.css"
],
"scripts": [],
"environments": {
"source": "environments/environment.ts",
"prod": "environments/environment.prod.ts",
"dev": "environments/environment.dev.ts"
}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"prefixInterfaces": false,
"lazyRoutePrefix": "+"
}
}
This is currently being designed and will be implemented before a final release. The general idea will be to provide a reference to a style file (CSS/SCSS/LESS...) and have it included within the application.
As mentioned before, it's being implemented for future releases. There's already a pull request to fix this. You can update it manually as a workaround for now.
Then, update your angular-cli.json file:
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": "assets",
"index": "index.html",
"main": "main.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"mobile": false,
"additionalEntries": [
{ "input": "polyfills.ts", "output": "polyfills.js" },
"styles.sass"
],
"environments": {
"source": "environments/environment.ts",
"prod": "environments/environment.prod.ts",
"dev": "environments/environment.dev.ts"
}
}
],

Resources