angular全局腳本

Global scripts

全局腳本

You can add Javascript files to the global scope via the scripts option inside your
project's build target options in angular.json.
These will be loaded exactly as if you had added them in a <script> tag inside index.html.
您可以通過angular.json中項目的構建目標選項中的 腳本 選項將JavaScript文件添加到全局范圍。這些將被加載,就像您將它們添加到 index.html 中的 <script> 標記中一樣。
This is especially useful for legacy libraries or analytic snippets.
這對舊版庫或分析片段尤其有用。

"architect": {
  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
      "scripts": [
        "src/global-script.js",
      ],

You can also rename the output and lazy load it by using the object format:
您也可以使用對象格式重命名輸出并延遲加載它:

"scripts": [
  "src/global-script.js",
  { "input": "src/lazy-script.js", "lazy": true },
  { "input": "src/pre-rename-script.js", "bundleName": "renamed-script" },
],

Note: you will also need to add any scripts to the test builder if you need them for unit tests.
注意:如果需要它們進行單元測試,您還需要將任何腳本添加到測試生成器。

Using global libraries inside your app

在應用程序內使用全局庫

Once you import a library via the scripts array, you should not import it via a import statement
in your TypeScript code (e.g. import * as $ from 'jquery';).
If you do that you'll end up with two different copies of the library: one imported as a
global library, and one imported as a module.
一旦通過腳本數組導入庫,您不應該通過TypeScript代碼中的import語句導入它(例如, import * as $ from 'jquery')

This is especially bad for libraries with plugins, like JQuery, because each copy will have
different plugins.
對于帶有插件的庫如JQuery來說,這是非常糟糕的,因為每個副本都會有不同的插件。

Instead, download typings for your library (npm install @types/jquery) and follow
the 3rd Party Library Installation steps,
this will give you access to the global variables exposed by that library.
相反,為你的庫下載類型 (npm install @types/jquery) 和 根據 3rd Party Library Installation 步驟, 這將使您可以訪問該庫公開的全局變量,

If the global library you need to use does not have global typings, you can also declare them
manually in src/typings.d.ts as any:
如果您需要使用的全局庫沒有全局類型,您也可以在 src / typings.d.ts 中手動聲明它們,如下所示:

declare var libraryName: any;

When working with scripts that extend other libraries, for instance with JQuery plugins
(e.g, $('.test').myPlugin();), since the installed @types/jquery may not include myPlugin,
you would need to add an interface like the one below in src/typings.d.ts.
處理擴展其他庫的腳本時,例如使用JQuery插件(e.g, $('.test').myPlugin();), 自安裝@types/jquery 可能不包含 myPlugin, 您需要在 src/typings.d.ts 中添加如下所示的端口。

interface JQuery {
  myPlugin(options?: any): any;
}

Otherwise you may see [TS][Error] Property 'myPlugin' does not exist on type 'JQuery'. in your IDE.
否則,你可能會看到 [TS][Error] Property 'myPlugin' does not exist on type 'JQuery'. 在你的IDE.

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容