如何创建所有脚本加载器都支持的angular2库

How to create angular2 library which could be supported by all script loaders

我如何创建一个 javascript 文件,其中包含一个 Angular 2 模块,可以被其他应用程序使用,但在运行时直接从中央服务器加载,而不是捆绑到一个具体应用程序的代码?

将其视为 Angular 2 库的 CDN。要求是该库的使用者将在其页面上包含一个脚本。

以这种方式实现它是一项要求,因此我对任何建议将库捆绑到单个应用程序的输出文件中的答案都不感兴趣。库脚本必须在运行时直接从库的服务器加载。

这是所需的工作流程(从高层次看)。

我对此做了很多研究,但我没有运气弄清楚。任何帮助将不胜感激。

您可以使用 ES6 + Angular2 + Webpack 来实现。

在此之前,让我解释一下什么是 umd 模块系统。

The UMD pattern typically attempts to offer compatibility with the most popular script loaders of the day (e.g RequireJS amongst others)

如上所述,UMD 是一种模式,其中使用此模式创建的库将支持所有 modules/script 加载程序,如 requirejswebpackbrowserifysystemjs 等。即遵循 UMD 模式的库将被所有主要模块系统识别(AMDCommonJSES6Vanilla JS).

这是 CDN 中所有库的工作方式。

现在,即使您也必须遵循相同的 UMD 模式。由于您的图书馆位于 angular2,我建议您选择 ES6Angular2Webpack

您必须设置这些配置以获取 UMD 格式的库,以便任何脚本加载程序都可以使用它。

output: {
    path: __dirname + '/lib', // path to output
    filename: outputFile, // library file name
    library: libraryName, // library name
    libraryTarget: 'umd', // the umd format
    umdNamedDefine: true // setting this to true will name the AMD module
  },

一旦您的 webpack 输出包准备就绪(umd 模块),那么任何用户都可以将您的库注入索引页面并开始使用您的 angular2 组件,无论他们使用什么脚本加载器/模块系统。

有个很好的例子here and he explained this here

问:我们图书馆的消费者如何在他们的 Angular 2 应用程序中包含这个 umd 包?

回答: 由于您的库将成为 UMD 模块,用户可以根据他们在应用程序中使用的脚本 loader/module 系统包含库。

例如。 香草 JS:

    <script src="http://example.com/your_lib.js"></script>
    <script>
        // Your_Lib will be available and will attach itself
        // to the global scope.
        var html = Your_Lib.render();
    </script>

RequireJS (AMD):

    <script src="http://example.com/require.js"></script>
    <script> requirejs config goes here </script>
    <script>
        define(['your_lib', function(Your_Lib) {
             var html = Your_Lib.render();
        }])
    </script>

SystemJS (CommonJS):

var map = {
            '@angular': 'node_modules/@angular',
             ....
            'your_lib': 'example.com/your_lib.js'
        };
        var config = {
            defaultJSExtensions: true,
            map: map,
            packages: packages
        };
        System.config(config);

然后您可以像往常一样导入您的库。

网页包:

在Index.html

在webpack.config.js

{
    externals: {
        // require("your_lib") is external and available
        //  on the global var Your_Lib
        "your_lib": "Your_Lib"
    }
}

并且您的图书馆将在全球范围内以 Your_Lib 的形式提供。