So I am trying to add some css style to my react components but failed.
My webpack.config.js looks like:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, './build');
var APP_DIR = path.resolve(__dirname, './src/client');
const config = {
entry: {
main: APP_DIR + '/index.js'
},
output: {
filename: 'bundle.js',
path: BUILD_DIR,
},
module: {
rules: [
{
test: /\.css$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader?modules=true&camelCase=true"
}]
},
{
test: /\.(jsx|js)?$/,
use: [{
loader: "babel-loader",
options: {
cacheDirectory: true,
presets: ['#babel/preset-react']
}
}]
}
],
}
};
module.exports = config;
My client code folder looks like:
Client
--style
----index.css
--index.js
index.css looks like:
body{
color: #555;
background: #f85032;
margin: 10px 30px;
}
Inside index.js, I am loading the css file using
import css from './style/index.css';
Then I do:
npx webpack
npm start
There's no error message in console output. The webpage shows up but there's no css style. Can someone please help me with this? Thanks!
It appears that if I do some inline css in index.html then it works? Any suggestion why this happens? Thanks!
Change to import './style/index.css'; and see if that works
I am just guessing here, since i can not see your index.js
From your webpack file i can see that you are using css modules.
This means that you can not just assign classes as you would usually do it, but you must get them from the css you imported.
Hence
'<div className="className">'
Becomes
'<div class=Name"' + css.className + '">'
The reason is thay css modules is doing some clever naming to always make the imported css unique to ensure you are not having any global scoping and conflicts (which is what you want with css modules)
UPDATE
I have tried to create a local setup with your webpack config. You can download it here (It is just a zip file).
Unzip and enter folder then run npm install and npm run webpack. You can now open build/index.html and see the result.
Maybe then you can see what you are doing differently?
Related
Ive added reveal.js to my rails 7 app and with a little tinkering I can switch between slides, however the transitions (eg, slide or fade) do not work.
In terms of installation:
yarn add reveal.js
application.js
import Reveal from 'reveal.js';
import Markdown from 'reveal.js/plugin/markdown/markdown.esm.js';
let deck = new Reveal({
plugins: [ Markdown ]
})
deck.initialize();
slides html:
<div class="reveal">
<div class="slides">
<section data-transition="slide"><h1>Horizontal 1</h1></section>
<section data-transition="fade"><h1>Horizontal 2</h1></section>
</div>
</div>
What I have done/tried
I dont have any javascript errors in my console so im thinking this might just some issue with the css / the way im importing the css. so far I have tried copying the reveal.scss content (from node_modules) into a file in my assets/stylesheets/reveal.scss with no luck:
Module parse failed: Unexpected character '#' (1:0)
12:31:02 js.1 | 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
12:31:02 js.1 | > #use "sass:math";
I also tried commenting out the lines (only 3) that use the math property, however that didnt work for me.
I tried importing the css direction (in assets/stylesheets/application.scss) with:
#import "reveal.js/dist/reveal"
// and
#import "reveal.js/css/reveal"
the file in dist is a .css file, while the other one has the contents that I copied before and showed the same error regarding sass:math.
Next I thought I might not have sass so I did yarn add sass and yarn add node-sass, which also didnt make the transitions work.
Now when I open the demo.html and index.html files (that come with the reveal.js dependency in the node_modules) in a browser tab transitions work seamlessly. Meaning it must have to do with how im importing the css/scss?
EDIT: webpack.config.js
const path = require("path")
const webpack = require("webpack")
module.exports = {
mode: "production",
devtool: "source-map",
entry: {
application: "./app/javascript/application.js"
},
output: {
filename: "[name].js",
sourceMapFilename: "[file].map",
path: path.resolve(__dirname, "app/assets/builds"),
},
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
]
}
It looks like you need to install and then add the appropriate loaders to your webpack config. Here is the official webpack documentation. It would look something like this:
const path = require("path")
const webpack = require("webpack")
module.exports = {
mode: "production",
devtool: "source-map",
entry: {
application: "./app/javascript/application.js"
},
output: {
filename: "[name].js",
sourceMapFilename: "[file].map",
path: path.resolve(__dirname, "app/assets/builds"),
},
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
},
}
I am trying to import css to my specific component of react app.
webpack config:
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
use: 'css-loader',
}),
}
but css is not applied.
I also included the main css inside index.html. Is it the reason why I cannot apply another css file?
<link rel="stylesheet" href="../style/style.css">
Can you suggest me what's missing?
It depends on the webpack version you're using. For example, if you're using Webpack 4, then your development config would be:
{
test: /\.s?css$/, // test for scss or css files
use: [
'style-loader', // try to use style-loader or...
{
loader: 'css-loader', // try to use css-loader
options: {
sourceMap: true, // allow source maps (allows css debugging)
modules: true, // allow css module imports
camelCase: true, // allow camel case imports
localIdentName: '[local]___[hash:base64:5]', // set imported classNames with a original className and a hashed string in the DOM, for example: "exampleClassName__2fMQK"
},
},
],
}
example.css (must use camel case instead of snake case)
.exampleClassName {
text-align: center;
}
example.js
import React from 'react';
import { exampleClassName } from './example.css';
export default () => (
<h1 className={exampleClassName}>I am centered!</h1>
)
For production, you'll want to use OptimizeCSSAssetsPlugin and MiniCssExtractPlugin :
minimizer: [
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
map: {
inline: false,
annotation: true
}
}
}),
],
{
plugins: [
new MiniCssExtractPlugin({
filename: `css/[name].[contenthash:8].css`,
chunkFilename: `[id].[contenthash:8].css`,
}),
]
}
When you run webpack to build your application for production, it'll compile the css and (when the webpack config is set up properly) will generate an index.html that automatically adds a link to the compiled stylesheet.
Webpack is a steep learning curve and there's a lot of missing options from the above examples, so if you're just trying to get it up and running, then I have a Webpack-React-Boilerplate that has (s)css modules imports and a lot more already configured for you. I've included notes within the webpack config files to help assist as to what each option is doing.
Otherwise, if you're trying to learn older versions of webpack, then you can eject the create-react-app and reverse engineer/look at their extensive webpack notes.
Introduction
I have already setup bundling for my Javascript files with webpack in my project. Now I am in the process of adding CSS files to the webpack configuration. So far, I have been including the CSS files manually in the HTML header by adding <link> elements for every CSS file I depend on (e.g. bootstrap, my own css, etc.). Obviously this is not very elegant and using webpack would be much better, so I would like to replace the link elements and bundle them via webpack.
This should be easy, everything is pretty much documented in the webpack documentation. After reading the documentation and experimenting a bit with webpack I have arrived at the configuration below which already works.
Problem
The problem with my current setup is that I would like to have proper source map support and that does not seem to work. By proper, I mean that I expect that when I run a development build with webpack and I inspect some element in Chrome DevTools, that I will see from which file and which line in the file a certain CSS class originated and that I can click on the CSS rules and the browser jumps to that file.
I do not want to have inline styles in the head element, because then the browser will show something like .foobar { <style>..</style>, rather then .foobar { app.css:154.
With my current setup I have all CSS files combined (but not minified) into one app.css file. This means that if I inspect a bootstrap class such as .btn then it appears as .btn { app.css:3003. However, what I want to achieve is that the browser shows it as .btn { bootstrap.css:3003.
So now I am trying to understand how webpack and the different plugins such as css-loader and min-css-extract-plugin apply CSS source maps, and how I can configure them to achieve a proper debugging experience.
I am not sure how relevant this is, but when I navigate in DevTools under Sources to webpack://./bootstrap/dist/css/bootstrap.css I see that it only contains a single line:
// extracted by mini-css-extract-plugin.
Webpack Setup
index.js:
window.jQuery = require('jquery/dist/jquery');
require('bootstrap/dist/css/bootstrap.css');
require('bootstrap/dist/js/bootstrap');
/* other dependencies */
webpack.config.js:
const devMode = process.env.NODE_ENV !== 'production';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module: {
rules: [
{ /* Javascript rules excluded */ },
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
plugins: [
new UglifyJSPlugin (),
new HtmlWebpackPlugin({
template: 'app/index.tpl.html'
}),
new MiniCssExtractPlugin({ filename: devMode ?
'[name].css' :
'[name].[hash].css'
})
],
Conclusion
It seems I just passed the rubber duck test. While I was writing this I arrived at a solution. I will still publish the question, maybe it can help others.
The problem was that I was also using the mini-css-extract-plugin for development and not just for production. I thought that I needed to do that, because when at first I was using the style-loaded I would get styles included in the header and the browser would show me all styles as .foobar { <style>..</style>.
However, the actual problem seemed to be, that I was not using devtools. So the solution was to add devtool: devMode ? 'cheap-module-eval-source-map' : 'source-map', to the webpack configuration to conditionally use the style-loader plugin during development builds and mini-css-extract-plugin during production builds.
webpack.config.js
{
test: /\.css$/,
use: [
{
- loader: MiniCssExtractPlugin.loader,
+ loader: devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
/* ... */
+ devtool: devMode ? 'cheap-module-eval-source-map' : 'source-map',
I try to create a simple rollup app's config and have some troubles with css.
This is my css file:
#import "normalize.css";
#import "typeface-roboto";
html, body, #root {
height: 100%;
font-family: Roboto, serif;
}
body {
background: url('./images/background.jpg');
}
And all what i have is 3 errors about not found resources.
This is my config file:
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
import replace from 'rollup-plugin-replace'
import postcss from 'rollup-plugin-postcss'
import html from 'rollup-plugin-fill-html'
import url from "rollup-plugin-url"
process.env.NODE_ENV = 'development'
const CWD = process.cwd()
const Paths = {
SRC: `${CWD}/src`,
DIST: `${CWD}/dist-rollup`,
NODE_MODULES: `${CWD}/node_modules`
}
Object.assign(Paths, {
INPUT: Paths.SRC + '/index.js',
OUTPUT: Paths.DIST + '/index.js'
})
export default {
input: Paths.INPUT,
output: {
file: Paths.OUTPUT,
format: 'iife', // immediately-invoked function expression — suitable for <script> tags
// sourcemap: true
},
plugins: [
html({
template: `${Paths.SRC}/template.html`,
filename: 'index.html'
}),
postcss({
modules: true,
plugins: [
]
}),
url({
limit: 10 * 1024, // inline files < 10k, copy files > 10k
}),
resolve(), // tells Rollup how to find date-fns in node_modules
babel({
exclude: 'node_modules/**'
}),
commonjs(), // converts date-fns to ES modules
replace({ 'process.env.NODE_ENV': JSON.stringify('development') })
]
}
I was tried to use some plugins like rollup-plugin-rebase and postcss-assets, but unfortunately, it did not help me.
Maybe i chose not common way, but single working solution for me is use postcss with 2 plugins: postcss-imports for #import syntax and postcss-url for url.
But there were difficulties too.
Postcss-url don't want just work, like i expect.
I had to use 3 instance of this plugin:
[
postcssUrl(), // Find files' real paths.
postcssUrl({
url: 'copy',
basePath: 'src',
useHash: true,
assetsPath: 'dist'
}), // Copy to required destination.
postcssUrl({
url (asset) {
const rebasedUrl = `dist/${path.basename(asset.absolutePath)}`
return `${rebasedUrl}${asset.search}${asset.hash}`
}
}) // Fix final paths.
]
You may see it in complex on https://github.com/pashaigood/bundlers-comparison
And of course, i will be glad to see more simple solution if you know that, please, share with me.
I've found css-import to work well, the NPM package provides a cssimport command line interface that accepts a main CSS file which includes #import statements and an optional list of directory in which to search for the CSS; it outputs to stdout the merged CSS which can be written to a single file.
I use the following to output a single main.css file in my build directory, searching for imported files under node_modules:
cssimport main.css ./node_modules/ > ./build/main.css
When using rollup you can use the rollup-plugin-execute plugin to execute a shell command as part of rollup's build process. For example:
plugins: [
...
execute('npx cssimport main.css ./node_modules/ > build/main.css')
]
I am writing a webpage with ReactJS.
I made a css stylesheet to change some bootstrap classes (for my Navbar fonts), added the link to html file, and it did not work. Then I installed style loaders and edited webpack.config file, but again server can't load css file. See below my webpack.config code .
var path = require("path");
var webpack = require('webpack');
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var config = {
entry: SRC_DIR + "/app/index.js",
output: {
path: DIST_DIR + "/app",
filename: "bundle.js",
publicPath: "/app/"
},
module: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["react", "es2015", "stage-2"]
}
},
{
test: /\.css?/,
loader: "style-loader!css-loader",
include: SRC_DIR
}
]
}
};
module.exports = config;
Having a link such as <link rel="stylesheet" type="text/css" href="/some/path/styles.css"> in your html file does not require a loader in webpack.config.js.
It sounds like you're getting a console error in the browser that says 404 file not found.
If that i the case then the href="/some/path/styles.css" part is not pointing to your file.
Furthermore, I assume, ( I know, dangerous... ) that you are trying to serve your css file from a public folder, and that your server possibly has this folder set as a static asset folder. If that is the case, you do not need to include that folder name in the path you used in the href of your link.
Hope this helps!
All you need to do is explicitly require CSS or Sass dependencies like you would its JS dependencies, and Webpack will build a bundle that includes everything you need. For Example
src/app/index.js
import 'bootstrap/dist/css/bootstrap.css'; //bootstrap installed via npm
import '../css/custom.css'; // just an example path
For more detail explanation Webpack Embedded Stylesheets