Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Angular sample #847

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 42 additions & 0 deletions examples/angular/.gitignore
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could probably be trimmed down to just /dist and /.angular/cache. The rest of the stuff isn't really relevant and/or is handled by the repo-root gitignore.

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.

# Compiled output
/dist
/tmp
/out-tsc
/bazel-out

# Node
/node_modules
npm-debug.log
yarn-error.log

# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*

# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings

# System files
.DS_Store
Thumbs.db
5 changes: 5 additions & 0 deletions examples/angular/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
dist
.angular
.vscode
README.md
Comment on lines +1 to +5
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, probably only .angular needs to be here`.

107 changes: 107 additions & 0 deletions examples/angular/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Angular

This example shows how to use vanilla-extract with Angular.

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 13.3.9.

**Note** this integration uses the Angular runtime to attach vanilla-extract class names to components. This works, and is probably fine for 99% of use cases. There is **probably** a more "Angular" way to do this where we could hook into the `styleUrls` feature of Angular components.

## Setup

Getting vanilla-extract working with Angular requires an extra step or two.

### 1. Pre-requisites

Vanilla-extract needs to integrate with your build step. If you're working As a lucky Angular user, the only option here is to extend your webpack config.

Follow the steps in the [Angular Builders repo](https://github.com/just-jeb/angular-builders/tree/master/packages/custom-webpack) to add a custom webpack config to your Angular app.

### 2. Webpack config

To make the necessary changes to the webpack config, some existing rules need to be modified. To do this, you have to use a config function in the custom webpack config file.

```javascript
// webpack.config.js

// e.g.

module.exports = (config) => {
// etc.
return config;
}
```

#### **1. Modify the Angular webpack loader & css-loader**

The Angular webpack loader will try and load all `*.ts` files. To avoid this, the current approach is to modify the loader config and exclude `.css.ts` files.

The existing css-loader (from the Angular webpack config) will try and handle `vanilla.css` files too - causing a conflict with the MiniCssExtract loader for vanilla-extract.

```javascript
config.module.rules = config.module?.rules?.map((rule) => {
// Exclude .css.ts files from angular loader
if (rule?.loader?.endsWith('@ngtools/webpack/src/ivy/index.js')) {
(rule.exclude ||= []).push(/\.css\.ts$/);
}
// Exclude .vanilla.css files from angular's css-loader implementation
if ('.css'.match(rule.test)) {
(rule.exclude ||= []).push(/\.vanilla\.css$/);
}
return rule;
})
```

#### **2. (optional) Add a typescript loader**

Because we excluded the `css.ts` files from the Angular webpack loader, if your setup doesn't include a typescript loader (a default Angular app doesn't seem to), then it'll be necessary to add a loader to handle the `css.ts` files.

Install the necessary dependencies;

```bash
npm i -D babel-loader @babel/core @babel/preset-env @babel/preset-typescript
```

```javascript
config.module?.rules.push({
test: /\.css\.ts$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-typescript',
['@babel/preset-env', { targets: 'defaults' }],
],
},
},
});
```

#### **3. Add vanilla-extract**

Finally, you can add vanilla-extract to the config, as per the docs.

Follow the instructions in the docs to [install vanilla-extract](https://vanilla-extract.style/documentation/getting-started/) and the [vanilla-extract webpack plugin](https://vanilla-extract.style/documentation/integrations/webpack/).

```javascript
config.plugins.push(new VanillaExtractPlugin());
```

```javascript
config.module?.rules.push({
test: /\.vanilla\.css$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: require.resolve('css-loader'),
options: {
url: false,
},
},
],
});
```

## A note on the webpack implementation

The webpack implementation mentioned here *works*, but it may be possible to instead provide an "emitter" to the Angular webpack plugin/loader to tell it how to handle these files. This would remove the need to exclude these files from the loader in the fairly invasive way we have. It would presumably also mean that adding the babel-loader is not necessary.
78 changes: 78 additions & 0 deletions examples/angular/angular.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular": {
"projectType": "application",
"schematics": {
"@schematics/angular:application": {
"strict": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"outputPath": "dist/angular",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": ["src/favicon.ico", "src/assets"],
"styles": ["src/styles.css"],
"scripts": [],
"customWebpackConfig": {
"path": "./webpack.config.js"
}
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {
"browserTarget": "angular:build"
},
"configurations": {
"production": {
"browserTarget": "angular:build:production"
},
"development": {
"browserTarget": "angular:build:development"
}
},
"defaultConfiguration": "development"
}
}
}
},
"defaultProject": "angular"
}
43 changes: 43 additions & 0 deletions examples/angular/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "vanilla-extract-example-angular",
"description": "Example Angular project using vanilla-extract and Sprinkles, compiling with webpack",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "~13.3.0",
"@angular/common": "~13.3.0",
"@angular/compiler": "~13.3.0",
"@angular/core": "~13.3.0",
"@angular/forms": "~13.3.0",
"@angular/platform-browser": "~13.3.0",
"@angular/platform-browser-dynamic": "~13.3.0",
"@angular/router": "~13.3.0",
"@vanilla-extract/css": "^1.9.0",
"@vanilla-extract/sprinkles": "^1.5.0",
"polished": "^4.2.2",
"rxjs": "~7.5.0",
"tailwindcss": "^3.1.8",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-builders/custom-webpack": "^13.1.0",
"@angular-devkit/build-angular": "~13.3.9",
"@angular/cli": "~13.3.9",
"@angular/compiler-cli": "~13.3.0",
"@babel/core": "^7.19.1",
"@babel/preset-env": "^7.19.1",
"@babel/preset-typescript": "^7.18.6",
"@types/node": "^12.11.1",
"@vanilla-extract/webpack-plugin": "^2.1.12",
"babel-loader": "^8.2.5",
"typescript": "~4.6.2"
}
}
3 changes: 3 additions & 0 deletions examples/angular/src/app/app.component.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.angular {
font-style: italic;
}
Comment on lines +1 to +3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be moved to global.css.ts.

15 changes: 15 additions & 0 deletions examples/angular/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<div [ngClass]="styles.layout">
<div [ngClass]="styles.card">
<div [ngClass]="styles.column">
<h1 [ngClass]="styles.heading">
<span role="img" aria-label="Waving hand"> 👋 </span>
<span role="img" aria-label="vanilla-extract logo"> 🧁 </span>
<span role="img" aria-label="Sprinkles logo"> 🍨 </span>
</h1>
<h2 [ngClass]="styles.subheading">
Hello from vanilla-extract and Sprinkles
<em class="angular">in Angular!</em>
</h2>
</div>
</div>
</div>
22 changes: 22 additions & 0 deletions examples/angular/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Attribute, Component, HostBinding } from '@angular/core';
import { style } from '@vanilla-extract/css';
import { sprinkles } from '../sprinkles.css';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sprinkles isn't used anywhere in this file. I think it would be a good idea to use sprinkles at runtime somewhere though, as the webpack example uses it both at buildtime and runtime, but this example currently only uses it within app.css.ts.

// Import the classes from the generated CSS file
import * as styles from './app.css';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
// Assign the classNames to a class property so it can be used in the template
styles = styles;

// We can also use the HostBinding decorator to bind the 'app' class to the host class attribute
@HostBinding('class') get classAttribute(): string {
return styles.app + ' ' + this.classNames;
}

constructor(@Attribute('class') public classNames: string) {}
}