Build additional CSS file in angular build - css

Background
#angular-builders/custom-webpack allows us to customize the webpack config of angular build, tutorial here. I am using it to build the additional scripts for web extension (Chrome/Firefox).
Here is the extra.webpack.config.js that I have included in angular.json
const { resolve } = require('path');
const scriptsDir = __dirname;
module.exports = {
entry: {
"background-script": resolve(scriptsDir, 'background-script/boot.ts'),
"fill-manager": [resolve(scriptsDir, 'fill-manager/boot.ts')],
"site-bridge": resolve(scriptsDir, 'site-bridge/boot.ts')
}
};
As expected it outputs background-script.js, fill-manager.js and site-bridge.js alongside angular build artifacts. As this webpack config is merged with the angular's webpack config, we can control all the optimizations, hashing, source maps etc from a single angular.json file.
Problem
I also want to bundle additional css files that would be used with extension scripts and be controlled by angular build.
I might be able to add specific rules, loaders etc to extra.webpack.config.js but I do not want to deal with postcss, autoprefixer and sass loaders etc as its already being done inside angular.
Just like script files, simply adding css entry inside extra.webpack.config.js does not produce css file i.e.
module.exports = {
entry: {
...
"fill-manager": [resolve(scriptsDir, 'fill-manager/boot.ts'), resolve(scriptsDir, 'fill-manager/main.css')],
...
}
};
Is there a way where I can specify a css/scss file entry in extra.webpack.config.js and it just output a bundled css file using configuration based on angular?

Related

How to generate different CSS bundle with Webpack 5

I have a React project with webpack (own configuration), from which I need to generate different packages with different styles. It would always be the same application, only in each package it generates, it would need a particular css file to end up in the package.
For example, in the repository I would have different css files:
- src
- index.js
- index.html
- themes
- theme1
theme1.css
- theme2
theme2.css
- theme3
theme3.css
and when I build it should look like this: (in "build" folder)
- build
index.html
main.css // with the styles of theme2, for example
bundle.js
I don't know how to do this with webpack or which plugin, hope you help me.
Thanks
You can get multiple separate CSS by adding multiple entries in your configuration.
Example:
webpack.config.js
module.exports = {
entry: {
main: "./path/to/your_main.js",
"css-theme-1": "./path/to/your/theme.css",
"css-theme-2": "./path/to/your/another-theme.css",
}
}
Also, you can build it into a folder by configuring filename properties in mini-css-extract-plugin.
Further reading:
Webpack Code Splitting

How to handle css modules with ?module suffix in Jest

I'm building a react app that mixes global css with css modules using Symfony's webpack encore. To avoid global CSS issues I've settled on using import 'app.css' for global styles and import styles from 'component.css?module' in my components. This is working as expected, however Jest is not pruning the ?module from the css module import and cannot find the file, giving me errors like Cannot find module './login.module.css?module' from 'assets/pages/Login/index.jsx'.
Does anyone know how to workaround this?
I managed to fix this myself. If anyone is interested, I enabled css modules in webpack.config.js by adding
.configureCssLoader((options) => {
options.modules = true;
})
However this then applies css module loading to all .css files and breaks global css rules.
So I modified the webpack config manually using the following at the end of webpack.config.js
const config = Encore.getWebpackConfig();
// only include files ending in module.css in the module css loader
config.module.rules[1].include = /\.module\.css$/;
// add another css loader without modules enabled to parse global css files
config.module.rules.push({
test: /\.css$/,
use: ["style-loader", "css-loader"],
exclude: /\.module\.css$/,
});
module.exports = config;
Not sure if this is the best way, but seems to be working ok at the moment!
I had some similar issue and fixed it with something like that (with Webpack Encore) :
.configureCssLoader(options => {
options.modules = {
auto: /\.module\.\w+$/i
}})
And now you can create a file with '.module.scss' suffix, and you can import it in a ts file. (working with jest, unlike ?module)

Using css-loader without React

I'm building a small web app with Webpack-enabled CSS modules (via css-loader) and without React. My goal is to get the benefits of short, obfuscated CSS class names (as I'm currently using lengthy BEM class names) in my HTML by using the localIdentName: '[hash:base64:8]' option on css-loader. Since I'm not using React, I'm working with raw HTML that is not being programmatically generated through JSX file or document.write.
I've used css-loader with React plenty before, and it ultimately works because you're able to import the style class names in the React file and refer to them using the human-readable names, regardless of whatever the class name gets changed to by Webpack.
However, I'm confused how to deal with this when using raw HTML; I can't just import the styles in since it's not a JS file. If I have a class called photo__caption--large referenced in my HTML, and webpack converts the class name to d87sj, the CSS file will say d87sj but the HTML will still say photo__caption--large.
Is there some kind of loader for HTML files that's able to edit class names in the file to their Webpackified equivalents? Or should I really just be using React with CSS modules?
This github code might help you.
https://github.com/moorthy-g/css-module-for-raw-html
A bit of complicated setup needed. We need to wire the following packages together.
- postcss-loader
- postcss-modules
- posthtml-css-modules
- posthtml-loader
The following postcss configuration creates modules dump file (./tmp/module-data.json).
// postcss.config.js
module.exports = {
plugins: {
'postcss-modules': {
getJSON: function(cssFileName, json) {
const path = require('path'), fs = require('fs');
const moduleFile = path.resolve('./tmp/module-data.json');
const cssName = path.basename(cssFileName, '.css');
const moduleData = fs.existsSync(moduleFile) ? require(moduleFile) : {};
moduleData[cssName] = json;
fs.existsSync('./tmp') || fs.mkdirSync('./tmp');
fs.writeFileSync(moduleFile, JSON.stringify(moduleData));
},
generateScopedName: '[local]_[hash:base64:5]'
}
}
}
And the following webpack rule links html file to modules dump file.
{
test: /\.html$/,
use: [
{ loader: 'html-loader' },
{
loader: 'posthtml-loader',
options: {
plugins: [
require('posthtml-css-modules')('./tmp/module-data.json')
]
}
}
]
}
Finally, HTML uses css-module attribute instead of class
<div css-module="main.container">
<h2 css-module="main.title">Title for the page</h2>
</div>
Let me know if you have any issues
My understanding of Webpack, CSS Modules, & CSS-Loader is that the entire point is to use javascript to generate the files.
This enables all the name translation and what not. What's your goal with Webpack if you're writing static HTML?
There are several static site generators for Webpack that will allow you to get the result you want, BUT they're still building the HTML files.
Alternately you could look at tools similar to React (Vue or Angular) that allow you to write all your "templates" in straight HTML. In Vue for example, you can write only HTML (to be compiled from javascript) without needing to use any of its data binding or routing.

Add the CSS from the node_modules folder using angular cli

I've installed a new library with npm, so far so good. Now I want to import the css in there to my project, obviously I shouldn't link directly to the node_modules folder. So, is there a simple to do import this to my project? I'm using Angular CLI.
I have an idea, but I'm not sure if it's a good idea - I thought about installing gulp/grunt and then require the style there and output it as vendor.css into my project. Is it even possible?
First go to your angular-cli-build.js file and add an entry in the vendorNPMFiles array. This will copy your node_modules files to the /vendor directory during the build. Now you can reference your css in your index.html as /vendor/folder/file.css.
Eg: angular-cli-build.js
/* global require, module */
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(js|js.map)',
'rxjs/**/*.+(js|js.map)',
'#angular/**/*.+(js|js.map)',
'bootstrap/dist/**/*.*',
'lodash/lodash.min.js'
]
});
};
index.html snippet
<link rel="stylesheet" href="vendor/bootstrap/dist/css/bootstrap.min.css">

Correct way to use Font Awesome SCSS in a Yeoman's Angular project

I created an Angular project using Yeoman's generator, and now I am trying to add the Font Awesome to the project. I installed it using Bower using
bower install fontawesome --save
then it automatically added to my app/index.html the following code:
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/fontawesome/css/font-awesome.css" />
<!-- endbower -->
<!-- endbuild -->
But I didn't want to use it as CSS, but as a SCSS import (to be able to change the URL of font files). So I deleted the above code from the HTML page and added the proper code into app/styles/main.scss:
$icon-font-path: "../bower_components/bootstrap-sass-official/assets/fonts/bootstrap/";
$fa-font-path: "../bower_components/fontawesome/fonts/"; // <==== here
// bower:scss
#import "bootstrap-sass-official/assets/stylesheets/_bootstrap.scss";
#import "fontawesome/scss/font-awesome.scss"; // <==== and here
// endbower
Then I run grunt build, but something (Grunt?) edited my files back to the original ones. The index.html got the <link> again and mine main.scss was kept only with the Bootstrap import.
Ok, we are almost there.
So I looked at the Bootstrap's bower.json and compared to the Font Awesome's bower.json and I saw the following difference:
// Bootstrap
"main": [
"assets/stylesheets/_bootstrap.scss", // it's SCSS
...
],
// Font Awesome
"main": [
"./css/font-awesome.css", // it's CSS
...
],
Then I found a way to properly (not sure) override the Font Awesome's bower configuration using my app's bower.json, and added the following code into it
"overrides": {
"fontawesome": {
"main": [
"./scss/font-awesome.scss", // now it's SCSS
"./fonts/*"
]
}
}
Question: Is this the correct way to use Font Awesome as a SCSS import and avoid Grunt of changing my files when building the project? By overriding its default "main" property?
Judging by your question I think you may be new to the web frontend build process. Unfortunately it can be a headache at times.
First off, note that SCSS != CSS and browsers do not know how to use SCSS. Including <link rel="stylesheet" href="main.scss"> in your HTML <head> tag will not work. We can enjoy the various perks of SCSS (e.g. variables, imports, etc.) during development, but to use these styles in the browser we must transpile SCSS into CSS (which the browser recognises).
To make developer's lives easier, it is common for seed projects (such as the one you are using) to include some kind of automated build process which includes transpiling SCSS into CSS. The build process is typically executed via a task runner, such as Grunt or Gulp. These seed projects/templates also typically include a task to inject your project's dependencies (as declared in your bower.json file) into your index.html automatically. A tool called wiredep is used to read through your bower.json files to determine these dependencies, in particularly, it will look for the 'main' attribute to determine which files a particular package requires. It will then inject the appropriate <script/> and <link> tags.
To explain this further, when you execute bower -install font-aweseome --save a few things happen:
The package is downloaded and added to your project (usually to bower_components/).
An entry is added to your bower.json file adding the package to your project's dependencies.
Each package includes its own bower.json file which describes its various properties, the most important of which (after name) is main. You can see the font-awesome bower.json file here. As you can see, it's main attribute references several files. These are the files that wiredep uses to determine which <script/> and <link> tags to inject into your index.html.
By specifying an override in your project's bower.json like this:
"overrides": {
"fontawesome": {
"main": [
"./scss/font-awesome.scss", // now it's SCSS
"./fonts/*"
]
}
}
You are specifying to wiredep that ./scss/font-awesome.scss and ./fonts/* are the files required by your project, and to ignore those listed in the font-awesome bower.json file.
Regarding SCSS: take a look at the Sass guide, in particular the section on imports. The Sass #import lets you split your styles across several smaller SCSS files (partials) that, upon transpilation, are combined and included into a single (optionally minified) CSS file. This includes any third party SCSS files that you import into your main.scss. For example, if you imported font-awesome.scss into your main.scss file, then transpiled it into CSS, the resulting CSS file would include all styles contained within font-awesome.scss.
To include and customize a third party SCSS file, what I do is:
Specify an import in my own custom main.scss file.
Make any customizations to variables I want.
Transpile main.scss into CSS.
Include a <link> tag to the transpiled CSS file in my index.html file.

Resources