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

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!

Related

NodeJS webpack configuration error for sass and css

I recently updated my NodeJS version to 'v16.13.2' and ever since then my template I built is breaking when trying to bundle the scss and css. Everything else works just fine when building.
I'm aware that node-sass had been deprecated and I should use sass (dart-sass). However, when I run my build I get this error:
Module parse failed: C:\Users\...\src\styles\styles.scss Unexpected token (1:3)
You may need an appropriate loader to handle this file type.
| h1 {
| color: white;
| text-align: center;
# ./src/app.js 25:0-31
# multi (webpack)-dev-server/client?http://localhost:8080 babel-polyfill ./src/app.js
I'm trying to get basic css to work but the loader doesn't seem to recognize the code.
Here is my code
package.json:
"scripts": {
"build:dev": "webpack",
"build:prod": "webpack -p --env production",
"dev-server": "webpack-dev-server",
"test": "cross-env NODE_ENV=test jest --config=jest.config.json",
"start": "node server/server.js",
"heroku-postbuild": "yarn run build:prod"
},
"dependencies": {
"babel-cli": "6.24.1",
"babel-core": "6.25.0",
"babel-loader": "7.1.1",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-object-rest-spread": "6.23.0",
"babel-polyfill": "6.26.0",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"css-loader": "^6.5.1",
"express": "4.15.4",
"extract-text-webpack-plugin": "3.0.0",
"firebase": "^8.9.1",
"history": "4.10.1",
"moment": "2.18.1",
"normalize.css": "7.0.0",
"numeral": "2.0.6",
"react": "^16.14.0",
"react-addons-shallow-compare": "15.6.0",
"react-dates": "12.7.0",
"react-dom": "^16.14.0",
"react-modal": "2.2.2",
"react-redux": "5.0.5",
"react-router-dom": "4.1.2",
"redux": "3.7.2",
"redux-mock-store": "1.2.3",
"redux-thunk": "2.2.0",
"sass": "^1.49.7",
"sass-loader": "7.3.1",
"style-loader": "0.18.2",
"uuid": "3.1.0",
"validator": "8.0.0",
"webpack": "3.1.0"
},
"devDependencies": {
"cross-env": "5.0.5",
"dotenv": "^14.2.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"enzyme-to-json": "^3.6.1",
"jest": "20.0.4",
"raf": "^3.4.1",
"react-test-renderer": "^16.14.0",
"webpack-dev-server": "2.5.1"
}
webpack.cnfig.js:
return{
entry: ['babel-polyfill','./src/app.js'],
output: {
path: path.join(__dirname, 'public', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.s?css$/,
use: CSSExtract.extract({
use: [
{
loader: 'css-loader',
options:{
sourceMap: true
}
},
{
loader: 'sass-loader',
options:{
sourceMap: true
}
}
]
})
}
]
},
EDIT: So after much research, I have also figured out that 'extract-text-webpack-plugin' is also deprecated and the documentation suggests that I use 'mini-css-extract-plugin'. So, I read the documentation for that and applied it but still nothing is working. I just want my webpack to bundle my .js and .css in separate files . Right now all of it is being pushed into 'bundle.js' and it does not render any css.
EDIT 2: Here is my new webpack.config.js and it is working as I wanted:
webpack.config.js:
webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
if(process.env.NODE_ENV === 'test'){
require('dotenv').config({ path: '.env.test'})
}else if(process.env.NODE_ENV === 'development'){
require('dotenv').config({ path: '.env.development'})
}
module.exports = (env) => {
const isProd = env === 'production'
return{
entry: ['babel-polyfill','./src/app.js'],
output: {
path: path.join(__dirname, 'public', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.(css)$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.(s[ca]ss)$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
}
]
},
plugins:[
new MiniCssExtractPlugin({
filename:'styles.css'
}),
new webpack.DefinePlugin({
'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
'process.env.FIREBASE_PROJECT_ID': JSON.stringify(process.env.FIREBASE_PROJECT_ID),
'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
'process.env.FIREBASE_MESSAGE_SENDER_ID': JSON.stringify(process.env.FIREBASE_MESSAGE_SENDER_ID),
'process.env.FIREBASE_APP_ID': JSON.stringify(process.env.FIREBASE_APP_ID)
})
],
devtool: isProd ? 'source-map' :'inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true,
publicPath: '/dist'
}
}
}
Alright I finally have an answer for all of this. So I essentially had to update a lot of my webpack due to deprecated modules. I ended up using 'mini-css-extract-plugin' and found out how to set it up. If anyone is working on a project using Nodejs version 16 and up, try this for the webpack and see if it works. I'll post my results in the initial question.

Chrome is not communicating changes in my browser to my local files

The Issue:
I'm trying to use chrome workspaces / source maps to update my sass partials as I edit CSS in chrome dev tools. Chrome is detecting my sass partials from source maps I setup in webpack, but giving me the error "Changes to this file were not saved to the file system." when I try to save the changes from the sources tab in chrome dev tools.
Moreover, in the styles tab of chrome dev tools, despite chrome knowing which properties are connected to which sass partials, changing the styles there doesn't update the partial files in the sources tab.
Chrome is not communicating changes in my browser to my local files, despite the sass partials showing up as source mapped in the chrome dev tools, and despite me setting up a workstation.
So far:
I set up a workspace in chrome and added the folder for the project
Disabled all my chrome extensions
Made sure 'enable css source maps' was true in chrome settings
I believe the problem might be my webpack config, since this is the first time I've made a custom webpack config, and I basically fiddled around with it until it worked. It could (probably not) be a problem with with a dependency, so I'll also add my package.json file.
Sass partial detected in chrome inspector
Sass partials showing up in sources tab:
Error Message
Webpack config file:
const path = require('path')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: ['#babel/polyfill', './src/index.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
contentBase: 'dist',
historyApiFallback: true
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/public/index.html'
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
test: /\.sass$/,
use: [
"style-loader",
{ loader: 'css-loader', options: { sourceMap: true} },
{ loader: 'sass-loader', options: { sourceMap: true } }
],
},
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
"babel-loader"
]
}
]
}
}
Package.json:
{
"name": "css",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/preset-env": "^7.6.3",
"#babel/preset-react": "^7.6.3",
"babel-eslint": "^10.0.3",
"babel-loader": "^8.0.6",
"css-loader": "^3.2.0",
"eslint": "^6.5.1",
"eslint-plugin-react": "^7.16.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.1",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2"
},
"dependencies": {
"#babel/polyfill": "^7.6.0",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2"
},
"eslintConfig": {
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"env": {
"browser": true,
"node": true
}
},
"eslintIgnore": [
"webpack.config.js"
]
}
This is no longer supported in Chrome :( Relevant issue is marked as "won't fix".
https://bugs.chromium.org/p/chromium/issues/detail?id=996226

Vuejs 2.5+ Webpack 4+ not loading CSS files

Currently I'm trying to setup a basic Vue project with webpack 4 enabled. The vue skeleton is based on the Microsoft SPA templates dotnet core. It seems to be that everything is running fine, except that external CSS files somehow are not loaded into the project and it is now bugging me for quite some time with the question why are those CSS files not loading.
What I basically did is 'dotnet new vue' (you need the Microsoft SPA templates installed) and after the creation of the project I started with updating the packages. Currently I have the following package.json file:
{
"name": "Dashboard",
"private": true,
"version": "0.0.1",
"scripts": {
"build:development": "webpack"
},
"devDependencies": {
"#types/webpack-env": "^1.13.6",
"ajv": "^6.5.2",
"aspnet-webpack": "^3.0.0",
"awesome-typescript-loader": "^5.2.0",
"bootstrap": "^4.1.1",
"coa": "^2.0.1",
"css-loader": "^1.0.0",
"event-source-polyfill": "^0.0.12",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file-loader": "^1.1.11",
"isomorphic-fetch": "^2.2.1",
"jquery": "^3.3.1",
"mini-css-extract-plugin": "^0.4.1",
"popper.js": "^1.14.3",
"style-loader": "^0.21.0",
"typescript": "^2.9.2",
"url-loader": "^1.0.1",
"vue": "^2.5.16",
"vue-loader": "^15.2.4",
"vue-property-decorator": "^7.0.0",
"vue-router": "^3.0.1",
"vue-style-loader": "^4.1.0",
"vue-template-compiler": "^2.5.16",
"webpack": "^4.16.0",
"webpack-cli": "^3.0.8",
"webpack-dev-middleware": "^3.1.3",
"webpack-hot-middleware": "^2.22.2",
"webpack-merge": "^4.1.3",
"webpack-node-externals": "^1.7.2"
},
"dependencies": {}
}
And this is my webpack.config.file:
const path = require('path');
const webpack = require('webpack');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const bundleOutputDir = './wwwroot/dist';
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
mode: 'development',
stats: {
modules: false
},
context: __dirname,
resolve: {
extensions: [ '.js', '.ts' ]
},
entry: {
'main': './ClientApp/boot.ts'
},
module: {
rules: [
{
test: /\.vue\.html$/,
include: /ClientApp/,
loader: 'vue-loader',
options: { loaders: { js: 'awesome-typescript-loader?silent=true' } }
},
{
test: /\.ts$/,
include: /ClientApp/,
use: 'awesome-typescript-loader?silent=true'
},
{
test: /\.css$/,
use: ['vue-style-loader', 'css-loader']
},
{
test: /\.(png|jpg|jpeg|gif|svg)$/,
use: 'url-loader?limit=25000'
}
]
},
output: {
path: path.join(__dirname, bundleOutputDir),
filename: '[name].js',
publicPath: 'dist/'
},
plugins: [
new VueLoaderPlugin(),
new CheckerPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
}),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
}),
new webpack.SourceMapDevToolPlugin({
filename: '[file].map',
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]')
})
]
};
And I have included the CSS file in the following ways:
In app.ts (I added them both just to test):
import '../navmenu/navmenu.css';
require('../navmenu/navmenu.css');
In boot.ts
import './components/navmenu/navmenu.css';
require('./components/navmenu/navmenu.css');
Or in the original file (navmenu.vue.html) (when a default SPA skeleton has been generated):
<style src="./navmenu.css" />
On all these locations the css file is not included/used in the frontend. I've also tried different approaches in the webpack.config file such as using the extract-text-webpack-plugin.
The basic idea behind is that the SPA template of Microsoft is using Webpack 2 (and other old versions of different packages) and I'm trying to update these to the latest versions.
Hopefully someone can help me out :-)
I've figured it out. Somehow webpack 4 is not picking up the CSS files by itself. You need to install the following plugin first:
MiniCssExtractPlugin
After that in the webpack config add the following configuration:
{
test: /\.(s*)[a|c]ss$/,
use: [
"vue-style-loader",
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
And add the mini css extract plugin also to the plugins section:
new MiniCssExtractPlugin({
filename: "[name].css"
})
And you should be good to go!
On your main.vue or any vue page inside style add #import "path"
<style>
#import "https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css";
#import "../assests/css/style.css"
</style>

Webpack 4 Production Build not loading Images and CSS

I am new to webpack so I am facing few issues below:
My GitHub repo
1. Here is the Problem :
My Webpack file :
const HtmlWebpackPlugin = require('html-webpack-plugin'); // Require html-webpack-plugin plugin
module.exports = {
entry: __dirname + "/src/app/index.js", // webpack entry point. Module to start building dependency graph
output: {
path: __dirname + '/dist', // Folder to store generated bundle
filename: 'bundle.js', // Name of generated bundle after build
publicPath: '/' // public URL of the output directory when referenced in a browser
},
module: { // where we defined file patterns and their loaders
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: [
/node_modules/
]
},
{
test: /\.(scss)$/,
use: [{
loader: 'style-loader', // inject CSS to page
}, {
loader: 'css-loader', // translates CSS into CommonJS modules
}, {
loader: 'postcss-loader', // Run post css actions
options: {
plugins: function () { // post css plugins, can be exported to postcss.config.js
return [
require('autoprefixer')
];
}
}
}, {
loader: 'sass-loader' // compiles Sass to CSS
}]
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
exclude: /node_modules/,
use: 'file-loader?name=fonts/[name].[ext]'
},
{
test: /\.(jpe?g|png|gif)$/,
exclude: /node_modules/,
use:'file-loader?name=images/[name].[ext]'
}
]
},
plugins: [ // Array of plugins to apply to build chunk
new HtmlWebpackPlugin({
template: __dirname + "/src/public/index.html",
inject: 'body'
})
],
devServer: { // configuration for webpack-dev-server
contentBase: './src/public', //source of static assets
port: 7700, // port to run dev-server
}
};
my folder structure :
My package.json
{
"name": "web",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --history-api-fallback --inline --progress",
"build": "webpack --mode production"
},
"author": "",
"license": "MIT",
"devDependencies": {
"autoprefixer": "^8.6.4",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"bootstrap": "^4.1.1",
"css-loader": "^0.28.11",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.2.0",
"jquery": "^3.3.1",
"node-sass": "^4.9.0",
"popper.js": "^1.14.3",
"postcss-loader": "^2.1.5",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"url-loader": "^1.0.1",
"webpack": "^4.13.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"roboto-fontface": "^0.9.0"
}
}
When I run npm run start I can see my application on browser with all CSS and Imagesloaded.
When I run npm run build I can see dist folder however When I run index.html from dist folder; I can't see any images and CSS loaded.
What I am doing wrong here?
Also I am building Static website so I will be having multiple HTML files along side e.g. home.html etc. so how can i link those pages accordingly?
As explained here Sass does not provide url rewriting, and all url(...)-like imports should be relative to the entry-file.
There is a specific Webpack plugin to automate that: resolve-url-loader.
It's meant to be configured just after sass-loader with source map enabled.
{
test: /\.(scss)$/,
use: [{
loader: 'style-loader',
}, {
loader: 'css-loader',
}, {
loader: 'postcss-loader',
options: {
plugins: function() {
return [
require('autoprefixer')
];
}
}
}, {
loader: 'resolve-url-loader'
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}]
},
When you develop your folder structure with a separate css folder like this:
index.html
css/main.css
You could forget to use that same relative path when building the project for production. In my case, I forgot to add the css/ prefix to the file name.
new MiniCssExtractPlugin({
filename: 'css/main.css',
}),
The css file became main.css but the JS entry point was looking for css/main.css
import '../css/main.css'

Stylus is not working with React

I'm helping create a webapp and we've recently switched to stylus and react. I've rewritten all the stylus lang files and written some react but the react is not being styled at all. Here is the component below.
import React, { Component } from 'react'
import Icon from 'react-component-bytesize-icons'
class CoursesCard extends Component {
render() {
const divStyle = {
backgroundImage : '/assets/img/animatingCourse.jpg'
}
return (
<div className='CoursesCard' style={divStyle}>
<div className='CardOverlay'>
<h3>What the courses is called?</h3>
<p>Last Checed</p>
<p>Users online</p>
</div>
</div>
)
}
}
export default CoursesCard
Here is the stylus lang code:
.CoursesCard {
width 32%
margin 10px 1%
float left
padding-top 20%
display inline-block
background white
box-shadow 0px 3px 20px #555
background-repeat no-repeat
background-size cover
cursor pointer
&.hover{
box-shadow 0px 3px 22px #333
}
.CardOverlay {
width 100%
height auto
padding 10px 0
background rgba(33,51,66,0.8)
color #fff
background-repeat no-repeat
background-size cover
cursor pointer
&.hover {
box-shadow 0px 3px 22px #333
}
h3{
font-size 18px
font-weight 500
margin-bottom 5px
margin-left 10px
}
p.lastChecked{
font-size 13px
font-weight 100
margin-bottom 5px
margin-left 10px
}
p.onlineUsers{
font-size 14px
font-weight 400
margin-left 10px
display block
}
}
}
Using Stylus in React requires a bundler like Webpack. I use Stylus + React a lot, so I can help but your question doesn't tell me if you have Webpack and npm or yarn set up.
Since I don't see your full build, I can share my build and maybe that will help. This is the closest I can get to helping you step-by-step without knowing more about your current build. Hope this helps!
Assuming you have Webpack and npm set up and your project has a package.json file already...
Run these commands in terminal...
npm install yarn
yarn init
yarn add poststylus autoprefixer-stylus autoprefixer
css-loader poststylus sass-loader style-loader stylus-loader
Make your webpack.config.js similar to this...
const path = require('path');
const postStylus = require('poststylus');
const webpack = require('webpack');
module.exports = {
context: __dirname,
entry: [
'./source/ClientApp.jsx',
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:8080/',
'webpack/hot/only-dev-server',
],
devtool: 'cheap-eval-source-map',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/public/',
hotUpdateChunkFilename: 'hot/hot-update.js',
hotUpdateMainFilename: 'hot/hot-update.json'
},
devServer: {
hot: true,
publicPath: '/public/',
historyApiFallback: true,
},
watch: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
// new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.LoaderOptionsPlugin({
options: {
stylus: {
preferPathResolver: 'webpack',
},
}
}),
],
resolve: {
extensions: ['.js', '.jsx', '.json', '.styl'],
modules: [
path.resolve('./source'),
path.resolve('./node_modules'),
],
},
stats: {
colors: true,
reasons: true,
chunks: true,
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/,
},
{
test: /\.jsx?$/,
loader: 'babel-loader',
},
{
test: /\.styl$/,
use: [
'style-loader',
'css-loader',
{
loader: 'stylus-loader',
options: {
use: [
postStylus(['autoprefixer']),
],
modules: true,
},
},
],
exclude: /node_modules/,
},
],
},
};
And here is my entire package.json if you need it for reference...
{
"scripts": {
"lint": "eslint **/*.{js,jsx} --quiet",
"clean": "rm -r public/bundle.js",
"build": "rm -r public/bundle.js && webpack",
"dev": "webpack-dev-server --watch --progress --colors",
"watch": "webpack --watch"
},
"dependencies": {
"autoprefixer": "^7.1.2",
"autoprefixer-stylus": "^0.14.0",
"axios": "^0.16.2",
"babel-core": "^6.25.0",
"babel-eslint": "^7.2.3",
"babel-loader": "^7.1.1",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-dynamic-import-webpack": "^1.0.1",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-preset-airbnb": "^2.4.0",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.24.1",
"concurrently": "^3.5.0",
"css-loader": "^0.28.4",
"d3": "^4.10.0",
"enzyme": "^2.9.1",
"eslint": "3.19.0",
"eslint-config-airbnb": "^15.0.2",
"eslint-config-airbnb-base": "^11.2.0",
"eslint-config-react": "^1.1.7",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^5.0.3",
"eslint-plugin-react": "^7.1.0",
"express": "^4.15.3",
"extract-text-webpack-plugin": "^3.0.0",
"firebase": "^4.2.0",
"firebase-tools": "^3.9.2",
"json-loader": "^0.5.7",
"node-sass": "^4.5.3",
"nodemon": "^1.11.0",
"poststylus": "^0.2.3",
"prop-types": "^15.5.10",
"react": "^15.6.1",
"react-date-range": "^0.9.4",
"react-dom": "^15.6.1",
"react-hot-loader": "3.0.0-beta.6",
"react-router-dom": "^4.1.2",
"react-test-renderer": "^15.6.1",
"resolve-url-loader": "^2.1.0",
"sass-loader": "^6.0.6",
"sort-package-json": "^1.7.0",
"style-loader": "^0.18.2",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.1",
"webpack": "2.6.1",
"webpack-combine-loaders": "^2.0.3",
"webpack-dev-middleware": "^1.11.0",
"webpack-dev-server": "^2.6.1",
"webpack-hot-middleware": "^2.18.2"
},
}
React has nothing to do with Stylus at all.
I suppose you are using Webpack as bundler of choice. If so, you have to configure Webpack so that it understands what to do with .styl files (or whatever file extension is used).
Webpack has concept of loaders - loader loads file, transforms it in some way and pushes output down the chain.
You need to add stylus loader. To do so, please take a look at this plugin's GH page

Resources