简体   繁体   中英

ES6 module import and dependency management

With the use of transpilers it is already possible to use ES6 modules. One of the easiest ways is using Browserify and Babelify. The problem I'm having is how to handle dependency management.

In the old days you'd just have some Bower dependencies. The build would bundle non-CDN to vendor.js and project specific files to foobar.js (or whatever). So then you'd be able to use the resulting code in a different project by simply bower install foobar --save . If both foobar and your new project had a common dependency it would be easily resolved with Bowers flat dependency.

Now in come ES6 modules: Say I have a project foo using lodash . The directory structure is as follows:

src/js/foo.js src/vendor/lodash/dist/lodash.min.js

And foo.js starts by declaring:

import * as _ from '../../vendor/lodash/dist/lodash.min.js';

or (as Browserify wants since Babelify transpiles to CommonJS):

import * as _ from './../../vendor/lodash/dist/lodash.min.js';

If I now round up and publish my foo project and start a new project bar that uses foo this will be my directory structure.

src/js/bar.js src/vendor/foo/dist/foo.js src/vendor/lodash/dist/lodash.min.js

But that would not work since the path from foo to lodash is now broken (if I understand Browserify correctly the dot-slash in './blaat/file.js' is relative to the file it's being called from).

Is some way to import without making any file path assumptions?

Isn't there some way to indicate multiple source roots? (ie in the above case src/js and src/vendor ... well, ideally you'd just want to state import * as _ from 'lodash'; )

I've only used Browserify with Babelify on cli. Should I be using some other transpiler?

I think that jspm is the solution your looking for. It will help you out without making file path assumptions when importing modules. It uses the SystemJS dynamic ES6 loader . Watch the video that is posted on their site for a very good explanation on how it all works, Guy Bedford: Package Management for ES6 Modules [JSConf2014] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM