当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - share AMD modules across files

问题描述:

I'm currently building the Ember.SimpleAuth library - a library for implementing authentication/authorization for Ember.js applications (https://github.com/simplabs/ember-simple-auth/tree/sub-packages). That library e.g. has functionality for authenticating the user of an Ember.js app. That authentication can be done via different strategies (e.g. login with credentials, login via Facebook etc.). What I want to do now is to split up the library so that everybody would include the base library in their apps plus a number of strategy libraries. e.g.:

<script src="../tmp/ember-simple-auth.js"></script>

<script src="../tmp/ember-simple-auth-oauth.js"></script>

To build the library I'm using an ES6 module transpiler that transpiles my source field to AMD and then I'm using a loader to build versions that can run in the browser: https://github.com/simplabs/ember-simple-auth/blob/sub-packages/vendor/loader.js.

The problem now is that the strategy libraries depend on stuff from the base library. But as both files have their own modules loader with different module registries included one file cannot see the modules defined in the other files. What I'm doing currently is to define a globally accessible module registry in the loader:

global.__ember_simple_auth_registry__ = global.__ember_simple_auth_registry__ || {};

var registry = global.__ember_simple_auth_registry__, seen = {};

so that all modules defined by Ember.SimpleAuth are globally accessible. But that of course doesn't seem great really. Is there a better approach for that? Or am I doing something wrong in general?

网友答案:

I found a solution for the problem. The problem only really only really exists in the browserified versions of the libraries where each library gets compiled into its own file with its own loader etc. When using "real" AMD where all files that are being used are registered with the same loader the problem doesn't exist because all files see all registered exports and can imply require each other. So I changed the extension libraries to use regular AMD requires and only updated the browserified versions so that they include "fake" AMD definitions for components that they depend on, e.g.:

define('ember-simple-auth/stores/base',  ['exports'], function(__exports__) {
  __exports__.Base = global.Ember.SimpleAuth.Stores.Base;
});

That way I can use clean AMD requires all over the place and still have the browserified versions working. I don't think that solution is too ugly but I'd be interested in feedback of course!

分享给朋友:
您可能感兴趣的文章:
随机阅读: