Always require certain dependencies in RequireJS

2019-07-21 09:26发布

问题:

I'm working on a Backbone project and I'm loading jQuery, Underscore and Backbone with RequireJS.

I find myself typing this pattern over and over again in all the modules:

define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) { ...

Is there a way or workaround to make these 3 libraries available to all modules without explicitly requiring them so I can concentrate on requiring extra things?

I though about loading this dependencies stack within script tags and use RequireJS for my modules and extra dependencies, but I'd lose the JamJS compile feature by having to concatenate jquery, underscore and backbone myself.

EDIT:

See Backbone Boilerplate: They are using JamJS too but they don't require backbone,underscore,jquery on each file. Somehow it's available to all of them.

They require the config.js file within the markup with RequireJS. This exports require.config stuff and then delegates to main.js. Within main, then they have magically access to Backbone!

What happened in the middle?

回答1:

I have a sandbox as mentioned in the comments. Here is a sample in coffee-script:

define [
  "core"
  "jquery"
  "extensions/backbone"
  "underscore"
], (core, $, backbone, underscore) ->

  util: 
    underscore: underscore
  mvc:
    Model: backbone.Model
    Collection: backbone.Collection
    View: backbone.View
    Events: backbone.Events
    Router: backbone.Router

This allows me to do

define ["sandbox"], (sandbox) -> class View extends sandbox.mvc.View

This is similar to the sandbox used in the AuraJS project and an implementation of the facade pattern which has the benefit that...

It lets you expose the parts of a JavaScript library that are safe to use instead of exposing the entire API. This is particularly useful when working in teams.

Also, in the future if I want to extend all views from a BaseView class instead of directly from Backbone.View, I just have to change the reference in my sandbox.



回答2:

Hello you can make globally accessible using the SHIM Config

Example taken from there:

shim: {
    'backbone': {
        //These script dependencies should be loaded before loading
        //backbone.js
        deps: ['underscore', 'jquery'],
        //Once loaded, use the global 'Backbone' as the
        //module value.
        exports: 'Backbone'
    },