如何将 javascript 应用程序拆分为多个文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8752627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:21:22  来源:igfitidea点击:

How can I split a javascript application into multiple files?

javascriptoop

提问by Mark Brown

I created a javascript application with all of the code in one file. The application has grown quite a bit and I think it's time to split it up into multiple files, but I'm having a hard time figuring out how to do this. I think the problem lies with how I have decided to build the app, which uses the following template:

我用一个文件中的所有代码创建了一个 javascript 应用程序。该应用程序已经增长了很多,我认为是时候将其拆分为多个文件了,但是我很难弄清楚如何做到这一点。我认为问题在于我如何决定构建使用以下模板的应用程序:

var myApp = function(){

    //there are several global variables that all of the modules use;
    var global1, global2, module1, module2;

    global1 = {
        prop1:1
    };

    //There are also several functions that are shared between modules
    function globalFunction(){

    }

    var ModuleOne = function(){

        function doSomething(){
            //using the global function
            globalFunction();
        }

        return{
            doSomething:doSomething
        }
    };

    var ModuleTwo = function(){

        function doSomething(){
            //module 2 also needs the global function
            globalFunction();

            //Use the functionality in module 1
            //I can refactor this part to be loosely coupled/event driven
            module1.doSomething();
        }
    };

    module1 = new ModuleOne();
    module2 = new ModuleTwo();
};

Even if all of the modules were loosely coupled and event driven, I still don't know how I would go about splitting this into multiple files given each module's reliance on the shared functions/variables. Does anyone have suggestions?

即使所有模块都是松散耦合和事件驱动的,我仍然不知道如何将其拆分为多个文件,因为每个模块都依赖于共享函数/变量。有没有人有建议?

采纳答案by nnnnnn

Take a look at the design pattern in this article: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth- you can split your module definition across multiple files in a way that lets common properties be shared but also lets you create variables or methods that are private just to a particular file.

看看这篇文章中的设计模式:http: //www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth- 您可以将模块定义拆分到多个文件中属性可以共享,但也允许您创建仅对特定文件私有的变量或方法。

The basic idea is that the individual JS files add to the same module with code like this:

基本思想是将单个 JS 文件添加到同一个模块中,代码如下:

var MODULE = (function (my) {
     var privateToThisFile = "something";

    // add capabilities...

     my.publicProperty = "something";

    return my;
}(MODULE || {}));

Where in each JS file if MODULEis already defined (from another JS file) you add to it otherwise you create it. You can set it up so that it (mostly) doesn't matter what order the various files are included in.

如果MODULE已经在每个 JS 文件中定义(来自另一个 JS 文件),则添加到其中,否则创建它。您可以对其进行设置,以便(大多数情况下)与各种文件包含的顺序无关。

The article details several variations, and of course you'll probably come up with your own tweaks...

这篇文章详细介绍了几种变化,当然你可能会想出你自己的调整......

回答by Jochem Van Der Spek

not to add to the confusion, but coming from a C++ background, I've tried to construct something that resembles something like a c++ namespace in the manner described below. it works, but I'd like to know if this is an acceptable pattern for the OP ?

不是为了增加混乱,而是来自 C++ 背景,我试图以下面描述的方式构建类似于 C++ 命名空间的东西。它有效,但我想知道这是否是 OP 可接受的模式?

--------------------------------file main.js:----------------

--------------------------------文件 main.js:------------ ---

var namespacename = function(){}

namespacename.mainvalue = 5;

namespacename.maintest = function() {
    var cm = new namespacename.game();
    cm.callme();
}

--------------------------------file game.js:----------------

-------------------------------- 文件 game.js: ------------- ---

namespacename.gamevalue = 15;

namespacename.game = function(){
    this.callme = function(){
        console.log( "callme" );
    }
}

namespacename.gametest = function() {
    console.log( "gametest:gamevalue:" + this.gamevalue );
    console.log( "gametest:mainvalue:" + this.mainvalue );
}

--------------------------------file index.html:--------------

--------------------------------文件 index.html:------------ ——

<html>
    <head>
        <title>testbed</title>
    </head>

    <body onload="init();">
    </body>

    <script type="text/javascript" src="main.js"></script>
    <script type="text/javascript" src="game.js"></script>

    <script type="text/javascript">

        init = function() 
        {
            namespacename.maintest();
            namespacename.gametest();

            console.log( "html main:" + namespacename.mainvalue );
            console.log( "html game:" + namespacename.gamevalue );
        }

   </script>
</html>

回答by jfriend00

You can put the shared functions and shared modules on the myApp object so they don't pollute the global namespace, but can be accessed anywhere without being inside the same closure.

您可以将共享函数和共享模块放在 myApp 对象上,这样它们就不会污染全局命名空间,而且可以在任何地方访问,而无需位于同一个闭包内。

myApp.moduleOne = function() {...}
myApp.moduleTwo = function() {...}
myApp.globalFunction = function() {...}

Then, you can define them in any file and use them in any file.

然后,您可以在任何文件中定义它们并在任何文件中使用它们。

You could also just break the file up into multiple files, but require them to be included in a specific order that preserves your closure. If you're breaking up the files for practical editing reasons, but recombining and minimizing them for actual deployment, then this wouldn't cost you anything in terms of how you write code or how it's deployed, but would give you lots of smaller files for editing convenience.

您也可以将文件分解为多个文件,但要求它们按特定顺序包含,以保留您的关闭。如果您出于实际编辑的原因分解文件,但为了实际部署而重新组合和最小化它们,那么这不会在您编写代码或部署方式方面花费任何费用,但会为您提供许多较小的文件为了编辑方便。

回答by Fabián Heredia Montiel

Give require.js a shot. http://requirejs.org/

给 require.js 一个机会。http://requirejs.org/

Example:

例子:

require(["dir/file"], function() {
    // Called when file.js loads
});

回答by slebetman

My favorite solution to this is use server side scripting to include the other files inside my "main" file. For example, using Perl's Template Toolkit:

我最喜欢的解决方案是使用服务器端脚本将其他文件包含在我的“主”文件中。例如,使用 Perl 的模板工具包:

var myApp = function(){
    [% INCLUDE lib/module1.js %]
    [% INCLUDE lib/module2.js %]
    [% INCLUDE lib/module3.js %]
}

Or PHP:

或 PHP:

var myApp = function(){
  <?php
    include 'lib/module1.js';
    include 'lib/module2.js';
  ?>
}