External code support

    When a script resource is imported into the Assets panel and Import as Plugin is set in the Inspector panel, the script resource is called a Plugin Script. Plugin scripts are usually used to introduce third-party libraries. Currently, only JavaScript plugin scripts are supported.

    Unlike other scripts in the project, Cocos Creator will not modify the content of the plug-in script, but some code may be inserted to adapt to Creator itself. In particular, Cocos Creator will shield the global variables , exports, define.

    Many third-party JavaScript libraries provide library functions in the form of global variables. These libraries often write global variables , global, self and .

    However, these global variables are not necessarily cross-platform. For convenience, when importing plug-in scripts, the option Simulate global variables is provided. After opening, Cocos Creator will insert the necessary code to simulate these global variables. Example:

    In the import checker, developers can specify dependencies to ensure the execution order of scripts.

    The plug-in script is copied to the build directory almost intact, so the usability and cross-platform of the plug-in script are not guaranteed by Cocos Creator. For example, when plug-in scripts use language features that are not supported by certain platforms, errors will result, especially:

    • Plugins that rely on the DOM API will not be able to publish to the native platform

    Plug-in scripts and non-plug-in scripts cannot interact in the form of import. For example, even if the developer knows that their target platform actually supports CommonJS, nor can it be used in a non-plug-in script forcibly through the relative path of require.

    Therefore, plug-in scripts generally communicate in the form of global variables (also known as IIFE module format), but the following points need to be noted:

    • Developers should use global variables very carefully. When you want to use global variables, you should be very clear about what you are doing. We do not recommend abusing global variables. Even if you want to use them, it is best to ensure that global variables are read only.

    • Developers can freely encapsulate or extend the Cocos Creator engine in the plug-in script, but this will increase the cost of team communication and make the script difficult to reuse.