Skip to content

Add PostCSS Assets to the CSS pre processing stack

Ameer Nuri edited this page Aug 13, 2016 · 3 revisions

In this example, we'll show how you can add postcss-assets to angular2-seed. PostCSS Assets is an asset manager for CSS. It isolates stylesheets from environmental changes, gets image sizes and inlines files.

  1. Install the npm dependency.
npm i --save-dev postcss-assets
  1. If you are not familiar with typings read this. Let's, create an external type definition because postcss-assets doesn't come with one and we use TypeScript. If you have typings installed globally* you can omit node_modules/.bin/ from the command below.
node_modules/.bin/typings search --ambient postcss-assets

You'll most likely see No results found searching ambient definitions as a response. Well yeah, that's a bummer, as of now we have to write it ourselves. Create postcss-assets.d.ts file under /tools/manual_typings with this content:

declare module 'postcss-assets' {

interface IOptions {
  loadPaths?: string[];
  basePath?: string;
  baseUrl?: string;
  relative?: boolean;
  cachebuster?: boolean | Function;
}

interface IAssets {
  (opts?: IOptions): NodeJS.ReadWriteStream;
}

const assets: IAssets;
export = assets;
}
  1. Copy /tools/tasks/seed/build.html_css.ts to /tools/tasks/project/build.html_css.ts. Open it up and edit it like this:
...
import * as assets from 'postcss-assets';
...
const processors = [
autoprefixer({
  browsers: BROWSER_LIST
}),
assets({
  basePath: APP_DEST,
  loadPaths: [join('assets', '**', '*')]
})
];
...
  1. Open toolbar.component.css and edit it like this:
more {
/* notice we use resolve and we don't have to specify the exact path of the image */
background: resolve("more.svg");
float: right;
height: 24px;
margin-top: 12px;
width: 24px;
}

Start the development environment gulp serve.dev and you can see the more.svg is still on its place. If you inspect it, you can see the resolved url.

* npm ls -g --depth 0 | grep typings if you see typings in the STDOUT you have it installed globally