简体   繁体   中英

How do you manage dependencies during concatenation?

I've been appending all my JS files together and load them in one lump sum so far, and that works great. I've been using grunt to load them. However, one thing I notice is order matters. If I have an inheritance chain such as Entity => Character => Player I need the Entity.js to be loaded first.

How can I control appending order and manage dependencies? Or is this a job for RequireJS?

Use a module bundler, such as Browserify , Webpack or RequireJS .

With browserify/webpack (or a commonjs loader and requirejs):

player.js

var Character = require('./character')
function Player() { Character.call(this) }
inherits(Player, Character)
module.exports = Player

character.js

var Entity = require('./entity')
function Character() { Entity.call(this) }
inherits(Character, Entity)
module.exports = Character

entity.js

function Entity() {}
module.exports = Entity

app.js

var Player = require('./player')
var player = new Player()

Or if you prefer AMD and requirejs (or using a Browserify/webpack AMD transform):

player.js

define(['./character'], function(Character) {
  function Player() { Character.call(this) }
  inherits(Player, Character)
  return Player
})

character.js

define(['./entity'], function(Entity) {
  function Character() { Entity.call(this) }
  inherits(Character, Entity)
  return Character
})

entity.js

define(function() {
  function Entity() {}
  return Entity
})

app.js

require(['./player'], function(Player) {
  var player = new Player()
})

It's worth noting here that webpack can load modules both sync and async: var sync = require('./sync') and require(['./async'], function(async) {}) .

Also replace inherits with whatever prototypal inheritance method you prefer. I prefer node.js's: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor or https://npmjs.org/package/inherits


ES6, the next version of javascript, has a spec for a module syntax. So sometime in the future proper module loading will be built into the language. It will likely look something like this:

import Character from "character"
function Player() { Character.call(this) }
inherits(Player, Character)
export default = Player

There are loaders for webpack and requirejs to load modules in this syntax as well: ES6 Module Transpiler (deprecated in favor of Babel and Esperanto ) and es6-loader (deprecated in favor of babel-loader ).

EDIT: es6ify now supports the es6 module syntax for use with browserify.


In my opinion, concatenating modules is old fashion. Use a module bundler and open the doors to the many wonderful things they provide.

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