How to removed unused selectors from prepending external scss files in SvelteKit? - sveltekit

I am using Scss with SvelteKit now, and I am prepending a Scss files to all <style> like this:
const config = {
compilerOptions: {
immutable: true
},
preprocess: preprocess({
scss: {
prependData: `
#use 'src/specific/vars.scss' as *;
`,
includePaths: ["../../node_modules", "../../libs"]
}
})
};
Unlike classes defined directly in <style>, unused classes from that prepended file will not be purged when build automatically. Is it possible to purge it like other classes?

Related

Prevent embedding small assets into HTML file

By default, Gatsby (properly also related to Webpack) will embed assets that are small enough into the HTML files in base64 encoding. I would like to prevent that from happening.
Is there an option from Gatsby that I can configure? Like something similar to IMAGE_INLINE_SIZE_LIMIT from CRA.
Alternatively, if the above is not possible, which Webpack config (it is related to Webpack, right?) should I modify to achieve what I'm looking for?
As mentioned in the comments, dataUrlCondition probably is what you are looking for.
exports.onCreateWebpackConfig = ({ stage, actions, loaders, getConfig }) => {
const config = getConfig();
actions.setWebpackConfig({
module: {
rules: [
{
parser: {
dataUrlCondition: {
maxSize: 4 * 1024,
},
},
},
],
},
});
};
Gatsby ships with his own webpack configuration but you can customize it using onCreateWebpackConfig API in your gatsby-node.js.
Regarding the parser, if a module source size is less than maxSize then it will be injected into the bundle as a Base64-encoded string, otherwise, the module-file will be emitted into the output directory.

How to move css-in-js (Styled Components) to an external css files during build using webpack - ReactJS

I am trying to figure out where the CSS files are residing when I build the react project. I am using webpack and I am able to make a single CSS file for all the styles used throughout the project if I use normal CSS. When I use CSS in js using styled component, I am not getting an external CSS file.
webpack.config.js
var path = require('path');
var hwp = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: path.join(__dirname, '/src/index.js'),
output: {
filename: 'index.js',
path: path.join(__dirname, './dist'),
publicPath : '/'
},
module:{
rules:[{
exclude: /node_modules/,
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/i,
use: [
{
loader : MiniCssExtractPlugin.loader,
options : {
publicPath: '/public/path/to/',
},
},
'css-loader'
]
}
]
},
devServer: {
historyApiFallback: true,
},
plugins:[
new hwp({template:path.join(__dirname, '/src/index.html')}),
new MiniCssExtractPlugin({
filename : '[name].css',
chunkFilename : '[id].css',
})
]
}
Contact.js
import React from 'react'
import styled from "styled-components"
const Container = styled.div`
background-color : red;
`
function contact() {
return (
<Container>
<h1>
Welcome to Contacts page
</h1>
</Container>
)
}
export default contact
This isn't supported by styled-components at the moment. From a project member -
We don't support static CSS extraction. You can try out emotion which does.
You might not need static CSS extraction actually, because of several reasons:
There's SSR which sends only critical CSS, instead of all static CSS, for the entire page. You don't even need to do SSR, but can use snapshotting (react-snapshot) or generate a static page (gatsby, et al), which basically saves a SSR result to a html.
Static extraction doesn't generate dynamic CSS, which means your page will either appear broken until the JS executes, or you'll need to defer until the JS is loaded
Caching doesn't actually buy you an advantage, because the JS bundles will likely always change in tandem with the extracted CSS
In v3 we will add preprocessing, which will actually a bigger advantage. As part of that we might support an option for static extraction, since the core library that will bring preprocessing will probably also be integrated into emotion, which does support extraction. So it might become an option. Or not 😉
Source
Emotion has also removed static css extraction
Duplicate of How can I opt for React Styled-Components to generate a physical CSS file?

Rollup Build failure for SCSS exports to be used in TS ( [!] Error: 'default' is not exported by src/styles/variables.scss )

I'm running into the following rollup build failure where I would like to be able to used exports from a scss file in my typescript files.
The build failure reads as follows:
[!] Error: 'default' is not exported by src/styles/variables.scss,
imported by src/components/Layout/Layout.themes.tsx
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
src/components/Layout/Layout.themes.tsx (1:7) 1: import vbl from
'../../styles/variables.scss';
My rollup config looks as follows:
import scss from 'rollup-plugin-scss';
import typescript from 'rollup-plugin-typescript2';
import image from '#rollup/plugin-image';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';
export default {
input: ['src/index.tsx'],
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: true,
name: 'Main'
},
{
file: pkg.module,
format: 'esm',
sourcemap: true,
name: 'tree-shaking'
}
],
external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {}), ...Object.keys(pkg.peerDependencies || {})],
plugins: [image(), scss({ output: 'dist/styles.css' }), typescript({ useTsconfigDeclarationDir: true }), terser()]
};
The variables.scss contains:
// colors
$color-blue: #1c4077;
$color-orange: #e87d1e;
:export {
colorBlue: $color-blue;
colorOrange: $color-orange;
}
The variables.scss.d.ts typings file contains:
export interface IGlobalScss {
colorBlue: string;
colorOrange: string;
}
export const variables: IGlobalScss;
export default variables;
And the Layout.themes.tsx file reads as follows:
import vbl from '../../styles/variables.scss';
export const myTheme = {
headerColor: vbl.colorBlue,
footerColor: vbl.colorOrange
}
I've tried an import of the non-default export import { variables } from '../../styles/variables.scss'; but it fails as well with:
[!] Error: 'variables' is not exported by src/styles/variables.scss,
imported by src/components/Layout/Layout.themes.tsx
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
src/components/Layout/Layout.themes.tsx (1:9) 1: import {
variables } from '../../styles/variables.scss';
I am able to serve the project via Storybook, however when I build via Rollup I encounter the error listed above. Please assist me in resolving this build failure?
Here is a CodeSandbox for this example. Extract the zip, yarn and run either yarn start or yarn build to test in VSCode. You'll notice that yarn start succeeds whereas yarn build will fail as mentioned above.
I think the problem is that the output property is not false.
Here is what the plugin does when that property is set to false:
if (options.output === false) {
const css = compileToCSS(code)
return {
code: 'export default ' + JSON.stringify(css),
map: { mappings: '' }
}
}
and this happens in the transform hook, which is invoked before the parsing takes place. This is important because export default ... is treated as a module, meaning you can import it in your js files.
So I think you'll have to manually bundle that variables file with:
scss({ output: false }).
Now, another problem arises: when you import from the .scss file, you'll get the :export object stringified.
For example:
"export default ":export {\n colorBlue: #1c4077;\n colorOrange: #e87d1e; }\n""
the plugin in use does not seem to handle this case.
So I think the solution involves manipulating that string so that you'd end up with something like this:
`{ colorX: 'value', colorY: 'value' }`

Use webpack modifyVars to override ant design default.less variables in create-react-app using react app rewired

I want to modify ant design default.less variables in my application that has been setup using create-react-app. I did not eject, but used react-app-rewired to modify inject custom webpack configurations. I am able to override most of the variable by following the link. I have the following directory structure:
--App
|--config-overrides.js
|--src
|--styles
|--styles.css
|--(maybe include a .less file to achieve the purpose)
config-overrides.js
const { injectBabelPlugin } = require('react-app-rewired');
const { compose } = require('react-app-rewired');
const rewireLess = require('react-app-rewire-less');
module.exports = function override(config, env) {
config = injectBabelPlugin(
['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }],
config,
);
config = rewireLess.withLoaderOptions({
modifyVars: {
'#ant-prefix' : 'ant',
'#primary-color': '#006778', //works
'#text-color': '#505050', //works
//Not able to inject styles this way.
"#{ant-prefix}-divider-vertical { height: unset; }" //doesn't work
},
javascriptEnabled: true,
})(config, env);
The app won't start with above when I add the last line in modifyVars object. I want to be able to override the antd classes like this.
eg:
.#{ant-prefix}-btn-primary {
&:hover,
&:focus {
background: #primary-color;
color: #fff;
}
}
modifyVars is only used to do exactly that. Modify variables. More specifically the variables in default.less.
You can't use it to inject CSS like that. This you will have to do in your own .css (or .less) file that you import into the app with a normal import command. (Import CSS in a react app)

Uncss Ignore option isn't working

I'm trying remove the css with uncss but it's removing all the styles no matter if they are listed on the ignore array.
The 2 files that I want to compare are just the index and the app.min.js which contains all the templates embedded in the javascript as strings, which are configured using $templateCache
take a look to the grunt task maybe there is something obvious that I'm missing:
uncss:{
production: {
options: {
ignore: ['.someclass', '.someclass', '.someclass','.etc_etc_class'],
stylesheets:['app.min.css']
},
files: {
'dist/app.min.css':['dist/index.html','dist/app.min.js']
}
}
}
any comment will be more than welcome!
The stylesheets option should have the full path of the css files relative to the root directory. So if the file is in dist/ add that to the stylesheets option.
For example:
uncss: {
dist: {
options: {
ignore : ['#added_at_runtime', /test\-[0-9]+/],
media : ['(min-width: 700px) handheld and (orientation: landscape)'],
raw : 'h1 { color: green }',
stylesheets : ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css'],
ignoreSheets : [/fonts.googleapis/],
urls : ['http://localhost:3000/mypage', '...'], // Deprecated
timeout : 1000,
htmlroot : 'public',
report : 'min'
},
files: {
'dist/css/tidy.css': ['app/index.html', 'app/about.html']
}
}
}
See: https://github.com/addyosmani/grunt-uncss

Resources