RequireJS:如何定义包含单个“类”的模块?

问题描述 投票:0回答:3

我有许多 JavaScript“类”,每个类都在自己的 JavaScript 文件中实现。对于开发,这些文件是单独加载的,对于生产,它们是串联的,但在这两种情况下,我都必须手动定义加载顺序,确保如果 B 使用 A,则 B 在 A 之后。我计划使用 RequireJS 作为实现CommonJS Modules/AsynchronousDefinition来自动为我解决这个问题。

有没有比定义每个导出一个类的模块更好的方法?如果没有,如何命名模块导出的内容?导出类“Employee”的模块“employee”(如下例所示)对我来说不够DRY

define("employee", ["exports"], function(exports) {
    exports.Employee = function(first, last) {
        this.first = first;
        this.last = last;
    };
});

define("main", ["employee"], function (employee) {
    var john = new employee.Employee("John", "Smith");
});
javascript commonjs requirejs
3个回答
114
投票

AMD 提案 允许您仅返回导出对象的值。但请注意,这是 AMD 提案的一个功能,它只是一个 API 提案,并且会使将该模块转换回常规 CommonJS 模块变得更加困难。我认为这没关系,但了解有用的信息。

因此您可以执行以下操作:

我更喜欢导出构造函数的模块以大写名称开头,因此该模块的非优化版本也将位于 Employee.js 中

define("Employee", function () { //You can name this function here, //which can help in debuggers but //has no impact on the module name. return function Employee(first, last) { this.first = first; this.last = last; }; });

现在在另一个模块中,您可以像这样使用 Employee 模块:

define("main", ["Employee"], function (Employee) { var john = new Employee("John", "Smith"); });
    

106
投票
作为 jrburke 答案的补充,请注意您不必直接返回构造函数。对于大多数有用的类,您还需要通过原型添加方法,您可以这样做:

define('Employee', function() { // Start with the constructor function Employee(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } // Now add methods Employee.prototype.fullName = function() { return this.firstName + ' ' + this.lastName; }; // etc. // And now return the constructor function return Employee; });

事实上,这正是 requirejs.org

此示例中显示的模式


0
投票
更新方法2023

define(function(){ return class Fullname{ constructor(firstname, lastname){ this.firstname = firstname this.lastname = lastname } generate() { return this.firstname+" "+this.lastname } } });
用途:

define(['your/modules/path'], function(Fullname){ let name = (new Fullname('Giang', 'Imgs')).generate(); console.log(name) }
    
© www.soinside.com 2019 - 2024. All rights reserved.