JSPM - Are there any advantages/disadvantages in i

2019-07-18 02:03发布

问题:

I'm starting to use JSPM in my Aurelia web projects and I want to know if there are any consequences or advantages in using the import "<client side library>" ?

I've seen code like so for client side libraries inside JS classes :

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

export class App {
    constructor {

    }
}

Question: What is the difference/advantages/disadvantages between importing it this way as oppose to the traditional include of <script> and <link> tags in the .html file?

<html>
<head>
   <link rel="stylesheet" src="<bootstrap path>/bootstrap.css">
</head>
<body>

   <script type="text/javascript" src="<bootstrap path>/bootstrap.js"></script>
</body>
</html>

My trial and error shows me that by using import in a particular class/js file, it limits the libraries to that particular view file as oppose to being globally available.

Ultimately when you go to build these project for production, don't these libraries need to exists in the index.html?

回答1:

My opinion is: you should use the import keyword, and here is why:

  • A matter of style: it's ES6-style, and Aurelia kinda obliges you to use it
  • Readability that matters: other developers would expect you to use import, so it might confuse them
  • Again, import takes care of loading that, so if you just add a script tag, you might add some import and then some function might be redeclared.
  • Beauty: I don't think it's very pretty to have 100 <script> tags in your code
  • Bundling for production. Are you going to concat and uglify all that with Grunt or Gulp? If so, that's extra work, because in the default config it comes out of the box. If no... well, no, you should do that
  • Rollup. And here comes the sweetest part.

JSPM is awesome! It's a little different to this project though – it combines a repository with a package manager and a client-side module loader, as opposed to simply bundling modules. JSPM allows you to use any module format and even develop without a build step, so it's a great choice for creating applications. Rollup generates smaller bundles that don't use the complex SystemJS format, and so is a better choice for creating libraries. A future version of JSPM may use Rollup internally, so you'll get the best of both worlds.

Rollup is another pro for using import. What it does is ripping the libraries you use and taking the minimal amount of code you need, so if you need only some stuff from, let's say, jQuery, you won't need to make your visitors download 50KB (or how much is it now?).

You can read more about Rollup here.