simple example for using require.js

后端 未结 3 631
广开言路
广开言路 2021-01-31 04:44

I am trying to learn how to use require.js. So I made an HTML page with the following tags in the body.



        
相关标签:
3条回答
  • 2021-01-31 05:12

    In addition to Domenic's answer maybe you prefer this way of using the define function without using require functions inside the modules.

    // shirt.js
    define({
        color: "black",
        size : "large"
    });
    
    // logger.js
    define(["shirt"], function (shirt) {
        return {
            logTheShirt: function () {
                console.log("color: " + shirt.color + ", size: " + shirt.size);
            }
        };
    });
    
    // main.js
    define(["shirt", "logger"],function (shirt, logger) {    
        alert("Shirt color is: " + shirt.color);
        logger.logTheShirt();
    });
    

    I prefer this way, but it's only a matter of taste I guess. (I'm assuming that all the scripts are on the same folder.)

    0 讨论(0)
  • 2021-01-31 05:21

    the contents of the main file should be a require call. for example, you have a values.js module containing:

    define({
        color: "black",
        size : "large"
    });
    

    in your main file (shirt.js), load the values.js as a dependency (assuming they are in the same directory):

    require(['values'],function(values){
        //values.color
        //values.size
    });
    
    0 讨论(0)
  • 2021-01-31 05:25

    In addition to Joseph's answer, you can also write other modules that depend on shirt (which is where the real power of RequireJS comes in).

    // shirt.js
    define({
        color: "black",
        size : "large"
    });
    
    // logger.js
    define(function (require) {
        var shirt = require("./shirt");
    
        return {
            logTheShirt: function () {
                console.log("color: " + shirt.color + ", size: " + shirt.size);
            }
        };
    });
    
    // main.js
    define(function (require) {
        var shirt = require("./shirt");
        var logger = require("./logger");
    
        alert("Shirt color is: " + shirt.color);
        logger.logTheShirt();
    });
    

    Then your HTML can just be

    <script data-main="../js/main" src="../js/require.js"></script>
    
    0 讨论(0)
提交回复
热议问题