AMD-建筑库示例 [英] AMD - Building library example

查看:89
本文介绍了AMD-建筑库示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议我在 AMD 上阅读,并可能重新考虑我的磁带库设置.目前,我已经使用 IIFE 方式对所有代码进行了编码,将所有小组件都隐藏在全局范围中.

It was suggested that I read on AMD and maybe rethink my library setup. For the moment I've coded all of it the IIFE way, hiding all the small components from the global scope.

但是,当我看到在 AMD 中仅define()种东西是多么容易时,我想尝试一下!

But when I saw how easy it is to just define() things in AMD, I wanted to try it out!

但是我遇到了两个问题,我似乎无法理解它从哪里开始以及如何加载内容.现在,请注意,我已经阅读了很多有关该主题的内容,并且一直在寻找答案,但是我认为这对我来说是一种误解,使我无法理解自己读过的内容.

But I ran into a couple of problems and I can't seem to understand where it starts and how things are loaded in. Now, be aware that I've read a lot on the subject and I searched for answers, but I think it's more a misconception on my part that blocks me from understanding what I read haha.

因此,我将以我的理解来询问! :)

So I will ask as I understand it! :)

因此,让我们从一个简单的示例开始(顺便说一句,我不想​​创建一个nodeJS模块,而是一个用于网站的标准库),假设我有以下代码:

So let's start with a simple example ( by the way I don't want to create a nodeJS module, but a standard library for websites ), let's say I have this code :

//----------------------------------------------
// main.js
//----------------------------------------------

var myLib = {}

//----------------------------------------------
// hello.js
//----------------------------------------------

myLib.hello = function() { console.log("hello"); }

//----------------------------------------------
// bye.js
//----------------------------------------------

myLib.bye = function() { console.log("bye"); }

我想将其转换为:

//----------------------------------------------
// main.js
//----------------------------------------------

define("myLib", ["hello". "bye"], function( hello, bye ){
    return {
        hello: hello,
        bye: bye
    };
});

//----------------------------------------------
// hello.js
//----------------------------------------------

define(function(){
    return function() { console.log("hello"); 
})

//----------------------------------------------
// bye.js
//----------------------------------------------

define(function() { 
    return function() { console.log("bye"); }
});


问题

  1. 如何将myLib附加到窗口对象(找到的内容)?您能否提供给我一个适用于myLib的示例?
  2. HTML中会发生什么?我需要多少个脚本标签才能完成这项工作?一:<script ... scr="loadMyLib.js"></script>?
  3. 据我了解,以AMD方式工作时需要requireJS作为依赖项,对吧?
  4. 我如何看待所有这些内容?我在想也许AMD仅适用于nodeJS?
  1. How do I attach myLib to the window object ( what I found ) ? Can you please provide me an example that works with myLib ?
  2. What happens in the HTML? How many script tags do I need to make this work? One : <script ... scr="loadMyLib.js"></script> ?
  3. As I understood, I need requireJS as a dependency when working the AMD way, right?
  4. Is there something wrong with how I see all of this? I'm thinking maybe AMD is meant only for nodeJS maybe?

为什么要改用AMD?

出于许多原因:

Why change to AMD?

For many reasons:

  • 我不必每次都写(function(){...})().
  • HTML中不再有脚本标签(只有一个脚本标签,库...和依赖项).
  • 更简单的:D

推荐答案

好,所以我终于明白了.这是我的做法:

Ok, so I finally got it down. Here is how I did :

  1. 下载 requireJS .
  1. Download requireJS.

据我了解, AMD 是用于编程的规范 语言JavaScript.它定义了一个应用程序编程接口 (API),用于定义代码模块及其依赖项,并加载它们 如果需要,异步进行. -维基百科

As I understood, AMD is a specification for the programming language JavaScript. It defines an application programming interface (API) that defines code modules and their dependencies, and loads them asynchronously if desired. - Wikipedia

RequireJS 实现 AMD .


  1. 创建您的项目设置.
  1. Create your project setup.

让我们创建以下项目:

./
|-- js
|   |-- lib
|   |   |-- jquery.js
|   |   |-- babana.js   // Whatever that is.
|   |   |-- require.js  // requireJS (YES).
|   |
|   |-- src
|   |   |-- methods
|   |   |   |-- hello.js
|   |   |   |-- bye.js
|   |   |
|   |   |-- core.js     // Core of our library.
|   |
|   |-- app.js  // Important
|
|-- index.html


  1. 创建您的 index.html 文件,然后插入 requireJS 脚本,如下所示:
  1. Create your index.html file and insert the requireJS script like so :

<script data-main="js/app" src="js/lib/require.js"></script>

这里发生了一些重要的事情:

There are some important things going on here :

  1. 好吧,您必须加载 require.js 库.
  2. 您必须在data-main属性中指定项目的源文件.将此文件作为库代码的入口点.在这种情况下: app.js .
  1. Well, you must load the require.js library.
  2. You must specify the source file of your project in the data-main attribute. See this file as the entry point to your library's code. In this case: app.js.

这一切看起来似乎令人困惑,但请放心,我们已经足够快到达目的地了. :)

This can seem confusing as of how it all comes together, but no worries, we are getting there soon enough. :)

  1. 设置 requireJS 配置 require 我们的库.
  1. Set requireJS configurations and require our library.

您还记得我们如何在script标签的data-main属性中指定源文件吗?让我们在其中添加所有需要的内容:

You remember how we specified the source file in the data-main attribute of the script tag? Let's add all we need in there :

//------------------------------
// js/app.js
//------------------------------

// Config
requirejs.config({
    baseUrl: 'js/src',
    paths: {
        pixi: '../lib/pixi',
        jquery: '../lib/jquery',
        banana: '../lib/banana'
    }
});

// Load our library.
requirejs(['core'], function( MyLib) {

    // Set it to the global scope.
    window.MyLib = MyLib;

});

发生了很多事情,所以我将提供一些解释.

There is a lot going on, so I'll provide some explanations.

  • baseUrl :每次我们要加载/请求js文件时,它将从我们在此处指定的url开始搜索所需的文件.在我们的情况下,我们将其设置为js/src,因为大多数文件都位于该位置.
  • 路径:您可以根据需要在此处手动设置所有路径.一个好主意是在此处设置外部库,因为您可以在库中请求它们. 还请注意如何编写../,这是因为它是从baseUrl开始的.
  • baseUrl: Every time we want to load/require a js file, it will search for the desired file starting at the url we specify here. In our case, we set it to js/src as most of our files are located there.
  • paths: You can manually set all the paths here if you want. A good idea is to set the external libraries here, as you may request them in your library. Also notice how you have to write ../, this is because it starts from the baseUrl.
  • 数组(可选):这是您的 request 数组.您将要加载的所有js文件插入此数组中. 注意,要使用已加载的函数或对象,您需要在函数旁边设置参数.在这里,我们加载core,提供它的参数是myLib.
  • 功能:这是动作功能.在这里,您将代码执行. 在程序中的某个时刻将库导出到全局范围很重要:窗口.
  • array (optional): This is your request array. You insert all the js files you want to be loaded in this array. Notice that to use a loaded function or object, you need to set a parameter in the function next to it. Here we load core and the parameter that provides it is myLib.
  • function: This is the action function. Here you put the code be executed. It is important at some point in your program to export your library to the global scope: window.
  1. 定义core和库的其余部分.
  1. Define the core and the rest of your library.

当然,有很多方法可以创建您的库结构.这是做到这一点的一种方法.检查 jQuery的设置.

There is, of course, a lot of ways to create your library structure. This is one way of doing it. Check jQuery's setup for some inspirations.

//------------------------------
// js/src/core.js
//------------------------------

define( [
    "./methods/hello",
    "./methods/bye"
], function( hello, bye ) {

"use strict";

var 
    version = "1.0",
    MyLib = function() { }; // Define a local copy of MyLib

MyLib.fn = MyLib.prototype = {
    constructor: MyLib, 

    // Loaded functions
    hello: hello,
    bye: bye
};

return MyLib;

});


//------------------------------
// js/src/methods/hello.js
//------------------------------

define( function() {
    return function() {
        console.log("hello");
    };
} );


//------------------------------
// js/src/methods/bye.js
//------------------------------

define( function() {
    return function() {
        console.log("bye");
    };
} );

好吧,我不会解释所有这些如何一起工作,因为这个答案已经很长时间了.但是你明白了.

Well, I won't explain how all of this works together, because this answer is already to long haha. But you get the idea.

  1. 在浏览器中使用您的库!

您的图书馆现在应该可以这样使用:

Your library should now be available like so :

MyLib.fn.hello()MyLib.fn.bye().

这篇关于AMD-建筑库示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆