What is the difference between linking stylesheets

2019-07-07 06:48发布

Using the VueJs and Webpack combo I have figured out that to include external stylesheets (for example bootstrap) you can do one of two things:

In your main js script you could require the stylesheet like this:

require('./assets/lib/bootstrap.min.css');

Or you could simply move it to a static folder accessed via Express and link it in your main html file:

<link rel="stylesheet" type="text/css" href="/static/css/lib/bootstrap.min.css">

What is the difference between these two approaches? I don't quite see the advantage of using require over a link (unless that works locally per component I guess?). Are there any advantages in using one over the other?

2条回答
Ridiculous、
2楼-- · 2019-07-07 07:15

Require approach:

  • bundled by webpack
  • some libraries may not bundle out-of-the-box and may need extra configuration
  • you can do various tricks like extracting all your CSS to one file
  • OTH you can decide not to split them to separate file, you can have all your CSS and JS in 1 file (very handy setup for development)
  • webpack can inline images into CSS and then into JS
  • hot reload of CSS should work in this approach (not useful for libraries)
  • big CSS like libs make the webpack dev server works slow as it have to rebuild them every time

Link approach:

  • not touched by webpack
  • can be served from external CDN on condition that you don't need to serve it from your server
  • not flexible
  • it just works

Webpack approach gives you much more flexibility and possibilities - it's very good for your code. I think my rule of a thumb would be not to bundle libraries if you don't have to, unless there is a reason for this as you pay with build time and sometimes extra configuration.

查看更多
成全新的幸福
3楼-- · 2019-07-07 07:15

In the first, the stylesheet is bundled by webpack into the file downloaded by the browser, and in the second, the browser is retrieving the stylesheet from the server directly.

Bundling your stylesheets using webpack's version of require assures that they are downloaded to the browser in one request (along with all the other assets your page requires to render) rather than downloading it as a separate server request. This reduces network traffic and speeds page rendering.

查看更多
登录 后发表回答