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')
]
Related
I am trying to set up a basic (css) library with vanilla TS and Vite 4.
I want to have a main js and css file at the top level so you can import the whole thing in one go. I also want to have component level imports where you can chose to just import the components js + css. The combined css and JS files are working fine; and the individual component JS file is working fine too.
Currently I'm running into the problem where I can't seem to keep an isolated version of the CSS files next to the JS files after bundling. My build is currently creating :
I've gone over the docs of both Vite and Rollup but I can't seem to figure out how to do the same to my CSS as I'm doing to my JS.
dist
--components
----button
------button.js
--main.css
--main.js
My preferred output would be:
dist
--components
----button
------button.js
------button.css
--main.css
--main.js
In my `main.ts` I'm importing:
import './style.scss'
import './tokens.scss'
import './components/button/button.scss'
vite.config.js
import { defineConfig } from 'vite'
import { resolve } from 'path'
export default defineConfig({
build: {
cssCodeSplit: false,
manifest: true,
rollupOptions: {
output: {
assetFileNames: () => 'main[extname]',
}
},
lib: {
formats: ['es'],
entry: {
main: resolve(__dirname, 'src/main.ts'),
button: resolve(__dirname, 'src/components/button/button.ts')
},
name: 'CSSFramework',
fileName: (_, fileName) => fileName === 'main' ? '[name].js' : 'components/[name]/[name].js',
},
},
});
Thanks in advance !
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 bundle my js and scss files in rollup ready for production.
Rollup takes all of my files and outputs them to a build dir, the result looks like this:
build
css
bundle.css
js
bundle.js
bundle.js.gz
As you can see, I am using the gzipPlugin for my js files.
I also want to use gzipPlugin to handle my css, but I cannot figure out how to do this.
My current setup looks like this:
import babel from "rollup-plugin-babel";
import { terser } from "rollup-plugin-terser";
import multi from "#rollup/plugin-multi-entry";
import gzipPlugin from "rollup-plugin-gzip"
import scss from "rollup-plugin-scss"
import del from "rollup-plugin-delete"
export default [{
input: "src/**/*.logic.js",
output: {
file: "build/assets/js/main.min.js",
format: "umd",
name: "Logic"
},
plugins: [
del({ targets: "build" }),
gzipPlugin(),
terser({
output: {
wrap_iife: false
}
}),
multi({
exports: true
}),
babel({
exclude: "node_modules/**"
})
]
}, {
input: "src/all.scss",
plugins: [
scss({
output: "build/assets/css/styles.min.css",
outputStyle: "compressed"
}),
]
}
];
My question is:
How can I get my outputted css file to be gzipped?.
I think I am missing something fairly simply, I just can't see how to get gzipPlugin working on the css file.... thanks in advance for any tips.
I think that you just need to add the gzipPlugin in the plugins session of your CSS generation.
Like this:
input: "src/all.scss",
plugins: [
scss({
output: "build/assets/css/styles.min.css",
outputStyle: "compressed"
}),
gzipPlugin()
]
I was able to accomplish this by specifying the additionalFiles option:
// rollup.config.js
...
import gzipPlugin from "rollup-plugin-gzip";
import css from "rollup-plugin-css-only";
export default {
input: "src/main.js",
output: {
...
file: "public/build/bundle.js",
},
plugins: [
gzipPlugin({
additionalFiles: ["./public/build/bundle.css"],
}),
css({ output: "bundle.css" }),
...
]
}
One little quirk I ran into was that the build has to be run twice. The first time without gzip to generate the bundle.css and the second time to gzip the bundle.css from the previous run.
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.
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?