How to import css file for into Component .jsx file - css

I am trying to use the react-day-pickers component like so but I can't figure out how to import the .css file and I keep getting the error:
Module parse failed:
/Users/qliu/Documents/workspace/AppNexus/pricing_ui/contract-ui/app_contract-ui/node_modules/react-day-picker/lib/style.css Unexpected token (3:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (3:0)
I have "css-loader": "^0.19.0", in my package.json installed and
here is my Calender.jsx file:
import React from "react";
import DayPicker, { DateUtils } from "react-day-picker";
import "../../../node_modules/react-day-picker/lib/style.css"; // <==== ERROR ON THIS LINE
export default class Calender extends React.Component {
state = {
selectedDay: null
};
handleDayClick(e, day, modifiers) {
if (modifiers.indexOf("disabled") > -1) {
console.log("User clicked a disabled day.");
return;
}
this.setState({
selectedDay: day
});
}
render() {
// Add the `selected` modifier to the cell of the clicked day
const modifiers = {
disabled: DateUtils.isPastDay,
selected: day => DateUtils.isSameDay(this.state.selectedDay, day)
};
return <DayPicker enableOutsideDays modifiers={ modifiers } onDayClick={ this.handleDayClick.bind(this) } />;
}
}
and this is my webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var settings = require('./src/server/config/settings');
var LessPluginAutoPrefix = require('less-plugin-autoprefix');
module.exports = {
devtool: '#source-map',
resolve: {
extensions: ['', '.jsx', '.js']
},
entry: [
'webpack-hot-middleware/client',
'./src/client/index.jsx'
],
externals: {
'react': 'React',
'react-dom': 'ReactDOM',
// to avoid duplicate import of React with react-addons-css-transition-group
'./React': 'React',
'./ReactDOM': 'ReactDOM',
config: 'config'
},
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
lessLoader: {
lessPlugins: [
new LessPluginAutoPrefix({ browsers: ['last 2 versions'] })
]
},
module: {
loaders: [{
test: /\.(js|jsx)$/,
loaders: ['babel'],
exclude: /node_modules/
},
{
test: /\.less$/,
loader: 'style!css!less'
},
{
test: /\.json$/,
loader: 'json-loader'
}]
}
};

How are you compiling this? If it's webpack, you'd probably need to bring in the style-loader and include something like this in the module.loaders array in your webpack config:
{
test: /\.css$/,
loader: "style!css"
}
Update: With the webpack.config.js now provided, we can confirm it needed a change in the module.loaders array. OP was using a less loader and only checking for .less files, so the exact loader object should read:
{
test: /\.(less|css)$/,
loader: 'style!css!less'
}
As suggested by #Q Liu. Leaving the original bit as if someone comes here with an error importing a .css file, it's likely what they need.

I used the following in my webpack config and it worked:
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],

JSX is not CSS. In your main HTML file, just add a <link> element to the CSS file, and the DOM generated by React will use it.

Related

Error importing mobiscroll css styles in webpack

I have a problem with importing mobiscroll css styles in my react project (created by webpack)
Other css files are working well but
This line generates Error:
import '#mobiscroll/react-lite/dist/css/mobiscroll.min.css'
The generated Error:
./node_modules/#mobiscroll/react-lite/dist/css/icons_mobiscroll.ttf?vtxdtu 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
./node_modules/#mobiscroll/react-lite/dist/css/icons_mobiscroll.woff?vtxdtu 1:4
Module parse failed: Unexpected character '�' (1:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
./node_modules/#mobiscroll/react-lite/dist/css/icons_mobiscroll.woff 1:4
Module parse failed: Unexpected character '�' (1:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
and my webpack.config.js:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CSSModuleLoader = {
loader: 'css-loader',
options: {
modules: {
localIdentName: "[name]__[local]___[hash:base64:5]",
},
sourceMap: true
}
};
const CSSLoader = { loader: 'css-loader' };
const PostCSSLoader = {
loader: 'postcss-loader',
options: {
ident: 'postcss',
sourceMap: false, // turned off as causes delay
plugins: () => [
autoprefixer({
browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9']
})
]
}
};
const StyleLoader = {
loader: 'style-loader'
};
const SassLoader = {
loader: 'sass-loader'
};
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js',
publicPath: ''
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}, {
test: /\.html$/,
use: [{loader: 'html-loader'}]
},
{
test: /\.(sa|sc|c)ss$/,
exclude: /\.module\.(sa|sc|c)ss$/,
use: [StyleLoader, CSSLoader, PostCSSLoader, SassLoader]
},
{
test: /\.module\.(sa|sc|c)ss$/,
use: [StyleLoader, CSSModuleLoader, PostCSSLoader, SassLoader]
},
{
test: /\.(svg|png|jpe?g|gif|bmp)$/,
loader: 'url-loader?limit=10000&name=img/[name].[ext]'
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file?name=[name].[ext]'
}
]
},
plugins: [
new CopyWebpackPlugin({
patterns: [ // for copying the content of 'public/static' folder to 'dist' folder
{ from: path.resolve(__dirname, 'public/static'), to: path.resolve(__dirname, 'dist/static')}
]
}),
new HtmlWebpackPlugin({
template: __dirname + '/public/index.html',
filename: 'index.html',
inject: 'body'
}),
]
};
my webpack configuration is working well for all other css or scss files but can not load that css file. what's the problem?
please help me with this.
I found out my mistake. I haven't defined a loader for font files and that css file was using some fonts.
This solved my Problem:
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
// exclude: /node_modules/,
loader: 'file-loader',
options: {
limit: 1024,
name: '[name].[ext]',
publicPath: 'dist/assets/',
outputPath: 'dist/assets/'
}
}

Combining tailwind css with sass using webpack

I'm struggling a bit getting Tailwind CSS to work with SASS and Webpack. It seems like the postcss configuration for tailwind doesn't really do anything in terms of processing #tailwind preflight, #tailwind components and #tailwind utilities
My set up is as follows:
layout.scss
#import "~tailwindcss/preflight.css";
#import "~tailwindcss/components.css";
.my-class {
#apply text-blue;
#apply border-red;
}
#import "~tailwindcss/utilities.css";
entry.js
import '../css/src/layout.scss';
postcss.config.js
const tailwindcss = require('tailwindcss');
const purgecss = require('#fullhuman/postcss-purgecss');
const cssnano = require('cssnano');
const autoprefixer = require('autoprefixer');
module.exports = {
plugins: [
tailwindcss('./tailwind.js'),
cssnano({
preset: 'default',
}),
purgecss({
content: ['./views/**/*.cshtml']
}),
autoprefixer
]
}
webpack.config.js
// NPM plugins
const autoprefixer = require('autoprefixer');
const WebpackNotifierPlugin = require('webpack-notifier');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: {
main: './scripts/entry.js'
},
output: {
filename: '[name].bundle.js',
publicPath: './'
},
watch: false,
externals: {
jquery: 'jQuery'
},
mode: 'development',
plugins: [
// Notify when build succeeds
new WebpackNotifierPlugin({ alwaysNotify: true }),
// Extract any CSS from any javascript file to process it as LESS/SASS using a loader
new MiniCssExtractPlugin({
fileame: "[name].bundle.css"
}),
// Minify CSS assets
new OptimizeCSSAssetsPlugin({}),
// Use BrowserSync plugin for file changes. I.e. if a CSS/SASS/LESS file changes, the changes will be injected directly in the browser with no page load
new BrowserSyncPlugin({
proxy: 'mysite.local',
open: 'external',
host: 'mysite.local',
port: 3000,
files: ['./dist/main.css', './views', './tailwind.js']
},
{
// disable reload from the webpack plugin since browser-sync will handle CSS injections and JS reloads
reload: false
})
],
module: {
rules: [
{
// Transpile ES6 scripts for browser support
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
// Extract any SCSS content and minimize
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()]
}
},
{
loader: 'sass-loader',
options: {
plugins: () => [autoprefixer()]
}
}
]
},
{
// Extract any CSS content and minimize
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{ loader: 'postcss-loader' }
]
}
]
}
};
When I run Webpack, everything runs just fine, but the content of /dist/main.css is:
#tailwind preflight;#tailwind components;#tailwind utilities;.my-class{#apply text-blue;#apply border-red}
I suspect it's related to the (order of) loaders, but I can't seem to figure out why it's not getting processed correctly.
Does anyone know what I'm doing wrong here? :-)
Thanks in advance.
Wow, so after fiddling around with the loaders even more, I made it work :-) For future reference:
I added options: { importLoaders: 1 } to the css-loader for SCSS files and removed: plugins: () => [autoprefixer()] from the postcss-loader in my webpack.config.js file.
Full, updated webpack.config.js file:
// NPM plugins
const autoprefixer = require('autoprefixer');
const WebpackNotifierPlugin = require('webpack-notifier');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: {
main: './scripts/entry.js'
},
output: {
filename: '[name].bundle.js',
publicPath: './'
},
watch: false,
externals: {
jquery: 'jQuery'
},
mode: 'development',
plugins: [
// Notify when build succeeds
new WebpackNotifierPlugin({ alwaysNotify: true }),
// Extract any CSS from any javascript file to process it as LESS/SASS using a loader
new MiniCssExtractPlugin({
fileame: "[name].bundle.css"
}),
// Minify CSS assets
new OptimizeCSSAssetsPlugin({}),
// Use BrowserSync plugin for file changes. I.e. if a CSS/SASS/LESS file changes, the changes will be injected directly in the browser with no page load
new BrowserSyncPlugin({
proxy: 'mysite.local',
open: 'external',
host: 'mysite.local',
port: 3000,
files: ['./dist/main.css', './views', './tailwind.js']
},
{
// disable reload from the webpack plugin since browser-sync will handle CSS injections and JS reloads
reload: false
})
],
module: {
rules: [
{
// Transpile ES6 scripts for browser support
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
// Extract any SCSS content and minimize
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader',
options: {
plugins: () => [autoprefixer()]
}
}
]
},
{
// Extract any CSS content and minimize
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{ loader: 'postcss-loader' }
]
}
]
}
};
There is an extension called tailwindcss-transpiler which compiles your layout.tailwind.scss files into pure CSS files.It also optimizing features.I hope it will be useful.
For VS Code
https://marketplace.visualstudio.com/items?itemName=sudoaugustin.tailwindcss-transpiler
For Atom
https://atom.io/packages/tailwindcss-transpiler

Window is not defined (Server-side rendering with Asp.Net SPA Services)

Thank you guys for reading my question. Really hoping for a solution to this, I've been trying to find a fix for days to no avail.
Here's the rundown: My goal is to render a React application on the server-side using .NET Core. I haven't even started with the react part yet, right now I'm simply trying to render an h1 tag with the ASP.NET Javascript Services Prerendering functionality.
On my first iteration, I wrote my boot-server.js file with es5 and it worked perfectly. However, I quickly realized I was going to need to compile the file through webpack in order for it to understand my React code.
As soon as I piped that file through webpack though, I got a "window is not defined" error which I haven't been able to fix. I understand that part of my application should not be aware of the window object since it lives in the server but setting the webpack config's target field to node does not seem to fix the issue. Below are all the files involved.
Here is my boot-server.js file:
import { createServerRenderer } from 'aspnet-prerendering';
module.exports = createServerRenderer((params) => {
return new Promise((resolve, reject) => {
var html = '<h1>Hello world!</h1>';
resolve({
html: html
});
});
});
Here is my cshtml view:
#addTagHelper "*, Microsoft.AspNetCore.SpaServices"
<app id="root" asp-prerender-module="wwwroot/client/boot-server.bundle">Loading...</app>
Here is my webpack.config.js file:
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const path = require("path");
const clientConfig = {
entry: './FrontEnd/index.js',
output: {
path: path.resolve(__dirname, "wwwroot/client"),
filename: "client.min.js",
publicPath: "/client/"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["es2015", "react", "stage-0"],
plugins: ["transform-class-properties", "transform-decorators-legacy", "react-html-attrs"]
}
}
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader?name=[name]_[hash:8].[ext]'
]
}
]
},
mode: 'development',
devServer: {
contentBase: './wwwroot/client',
hot: true
}
};
const bootServerConfig = {
stats: { modules: false },
resolve: { extensions: ['.js'] },
output: {
filename: '[name].js',
publicPath: '/wwwroot/client/', // Webpack dev middleware, if enabled, handles requests for this URL prefix
libraryTarget: 'commonjs'
},
entry: {
'main-server': './FrontEnd/boot-server.js'
},
module: {
rules: [
{
test: /\.js$/,
include: /FrontEnd/,
use: [
{
loader: "babel-loader",
options: {
presets: ["es2015", "react", "stage-0"],
plugins: ["transform-class-properties", "transform-decorators-legacy", "react-html-attrs"]
}
}
]
},
{
test: /\.svg$/,
use: {
loader: 'url-loader',
options: { limit: 25000 } //?limit=100000'
}
}
]
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './wwwroot/client')
},
target: 'node'
}
module.exports = [clientConfig, bootServerConfig];
Here is a screenshot of the error page:

unable to load css in react js

my all css files placed under src/assets/css/* and i am trying to import or load css file inside my component, i have tried to load css with below webpack configuration
Webpack file
{ test: /\.css$/, loader: "style-loader!css-loader" }
Component
import './../../assets/css/bootstrap.min.css';
Also tried to load css in index.html file like <link rel="stylesheet" href="/src/assets/css/bootstrap.min.css">
Also, is there a way if i have 5-6 css files by which i dont need to load all files in every component like if we can add in <head> tag
Here is my webpack.config file. I have used foundation instead of bootstrap but the webpack configuration is similar.
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'script!jquery/dist/jquery.min.js',
'script!foundation-sites/dist/js/foundation.min.js',
'./app/app.jsx'
],
externals: {
jquery: 'jQuery'
},
plugins:[
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
})
],
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
root: __dirname,
modulesDirectories: [
'node_modules',
'./app/components',
'./app/api'
],
alias: {
applicationStyles: 'app/styles/app.scss',
actions: 'app/actions/actions.jsx',
reducers: 'app/reducers/reducers.jsx',
configureStore: 'app/store/configureStore.jsx'
},
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0']
},
test:/\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
},
sassLoader:{
includePaths: [
path.resolve(__dirname, './node_modules/foundation-sites/scss')
]
},
devtool: 'cheap-module-eval-source-map'
};
And yes you can bundle the css in one file with webpack and import it in the root component.
Check my github repo for more details- https://github.com/hmachaharywork/ReactTodo
Use Extract text plugin. Only import this plugin in your webpack.conf.js
const ExtractTextPlugin = require("extract-text-webpack-plugin");
and refactor your rule like:
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
Finally, push new instance in plugin list:
plugins: [
new ExtractTextPlugin("styles.css"),
]

Webpack - Export SASS (.scss) files

I have a package and i want export my SASS variables to other packages use it. Currently my all .scss files are compiles and put in /dist/main.css file. My webpack config:
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: ['./src/index.js'],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.(scss|sass|css)$/,
loader: ExtractTextPlugin.extract("style", "css!sass")
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=10000&name=fonts/[hash].[ext]'
},
{
test: /\.scss$/, loader: 'style!css!sass!sass-resources'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: __dirname + '/build',
publicPath: '/',
filename: 'index.js',
library: 'Supernova',
libraryTarget: 'umd'
},
externals: {
'react': 'react',
'react-dom': 'react-dom'
},
plugins: [
new ExtractTextPlugin("[name].css")
]
};
My objective is create a package like bootstrap-sass.
If you want to make the variables you use within your sass files available to consumers of your published package, then you'll need to look at some special configuration for node-sass.
Currently (and as of the time you posted this) node-sass supports writing your own custom sass functions in javascript: https://github.com/sass/node-sass#functions--v300---experimental
This is untested, but we did this a while ago at a company i worked for...to do what you want, you'd need something like:
src/
your-package.js
your-styles.scss
tools/
constants/
colours.js
webpack/
...
base.sass.js
base.js
development.js
production.js
sass/
functions/
colours.js
# tools/webpack/base.sass.js
const Config = require('webpack-config').default
import {
signature as ColourSignature,
handler as ColourHandler
} from '#tools/sass/functions/colours
module.exports = new Config()
.merge({
module: {
rules: [
{
test: /\.scss$/,
use: [
...
{ loader: 'sass-loader',
options: {
sourceMap: true,
functions: {
[ColourSignature]: ColourHandler
}
}
},
]
}
]
}
})
# src/your-package.js
import Colours from '#tools/constants/colours'
import "./your-styles.scss"
export default YourAwesomeComponent {
static Colours = Colours
}
export const colours = Colours
# src/your-styles.scss
.your-awesome-component {
background-color: ColourGet(veganvomit, sobrightithurts);
}
# tools/sass/functions/colour.js
import Colours from '#tools/constants/colours'
export signature = 'ColourGet($name, $shade: default)'
export handler = function(name, shade) {
const colour = Colours[name]
if (!colour) return
if (typeof colour === 'string') return colour
return colour[shade]
}
# tools/sass/constants/colours.js
export default {
veganvomit: {
sobrightithurts: "darkkhaki",
light: "#D2691E",
default: "#8B4513",
somethingsomethingsomethingdarkside: "#000"
}
}
So now when you publish your package, they can access sass variables from your default export YourAwesomeClass.Colours or they can import it directly `import { Colours } from 'your-awesome-package'
I highly recommend using webpack-merge to separate out your Sass config to make it easy for other packages to use it. For your current config, I would do three things:
Add webpack-merge to your project (npm i --save-dev webpack-merge).
Put your Sass config into a separate file, named something like webpack.sass-config.js. Have it include the following:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
exports.config = function(options) {
return {
module: {
loaders: [
{
test: /\.(scss|sass|css)$/,
loader: ExtractTextPlugin.extract("style", "css!sass")
},
{
test: /\.scss$/, loader: 'style!css!sass!sass-resources'
}
]
},
plugins: [
new ExtractTextPlugin("[name].css")
]
}
}
// Side note: returning a function instead of a plain object lets
// you pass optional parameters from your main config file. This
// is useful if you want to make something like your compiled css
// file name different for another Webpack project without having
// to edit your Sass configuration file.
Update your webpack.config.js to the following:
var merge = require('webpack-merge');
// import your separated Sass configuration
var sassConfig = require('webpack.sass-config');
// Define your common config for entry, output, JSX, fonts, etc.
var common = {
entry: ['./src/index.js'],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=10000&name=fonts/[hash].[ext]'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: __dirname + '/build',
publicPath: '/',
filename: 'index.js',
library: 'Supernova',
libraryTarget: 'umd'
},
externals: {
'react': 'react',
'react-dom': 'react-dom'
}
};
// Merge your common config and Sass config
var config = merge(
common,
sassConfig.config()
);
// Export the merged configuration
modules.exports = config;
Obviously, this can go far beyond just your Sass config. I use webpack-merge to separate my development config from my production config. This article on Survive JS is a great resource for how to make the most of your Webpack setup.

Resources