Importing CSS and controlling order in <head>

2019-03-18 21:27发布

问题:

I've written the following in an Aurelia app

import "bootstrap/css/bootstrap.css!";
import "./app.css!";

and I want app.css second in since it overrides bootstrap.css styles. However, I'm getting app.css first since I presume the system.js loader is running them in parallel and since app.css is the smaller of the two it gets loaded first.

Is there a way in jspm to define a dependency between these two files to control their loading order is is there some other way?

Many thanks in advance! :)

回答1:

You could try to import the css using System.import. E.g. in your index.html:

System.import('bootstrap/css/bootstrap.css!').then(() => {
    System.import('./app.css!');
});

But keep in mind that this way you have to make sure that system.js is served with your app. So you can't bundle your whole app as an self-executing bundle.



回答2:

We have some stuff in the pipeline that should help you with this issue. If you check out this:

<template>
  <require from="nav-bar.html"></require>
  <require from="bootstrap/css/bootstrap.css"></require>

  <nav-bar router.bind="router"></nav-bar>

  <div class="page-host">
    <router-view></router-view>
  </div>
</template>

I know that Aurelia will be passing the CSS files to the loader in order, but I'm not sure if we'll be able to guarantee loading order. Hopefully Rob can come over here and give a proper answer to this, though. I'll point him in this direction.



回答3:

I had exactly the same problem. Controlling order of CSS is not possible in JSPM. I solved this problem with SASS and some tricks. Here's what I've done:

In html you give main element some id:

<html id="some-id">

Then you create sass file that will host your overrides (_overrides.scss):

#some-id {
  @import "buttons";
}

Now your buttons.scss can override styles from bootstrap (_buttons.scss):

.btn-default {
  background-color: #B6B3C7;
  border-color: #B33A3A;
}

This works thanks to the principle in CSS - most specific selector wins. By wrapping all your customizations in #some-id in scss it will produce code with every bit of code that is imported into curly braces prefixed by #some-id. This way your selector will always be more specific than bootstrap one and will override it.

I don't know if this will be sufficient for you as you don't mention scss, but it was for me.



回答4:

I've faced similar issue during development. The code below has helped me solve my problem. Now everything is loading exactly the way I want it.

System.import('bootstrap/css/bootstrap.css!').then(() => {
  System.import('./app.css!');
});

Thanks LazerBass for this suggestion.