Twi*_*ron 11 systemjs webpack umd angular
如何创建一个包含Angular 2模块的javascript文件,该模块可以被其他应用程序使用,但是在运行时直接从中央服务器加载并且不捆绑到特定应用程序的代码中?
可以将其视为Angular 2库的CDN.要求是此库的使用者将在其页面上包含单个脚本.
这是以这种方式实现它的要求,所以我对任何建议将库捆绑到单个应用程序的输出文件中的答案不感兴趣.必须在运行时直接从库的服务器加载库脚本.
CustomAuthModule
这是所需的工作流程(从高级别).
http://server-url/CustomAuth/script
.不应要求消费者知道有关systemjs或webpack等模块加载器的任何信息.我已经做了很多关于这方面的研究,我没有任何运气可以搞清楚.任何帮助将不胜感激.
您可以使用ES6
+ Angular2
+来实现这一点Webpack
。
在开始之前,让我解释一下什么是umd
模块系统。
UMD 模式通常尝试提供与当今最流行的脚本加载器的兼容性(例如 RequireJS 等)
如上所述,UMD
是一种模式,使用此模式创建的库将支持所有模块/脚本加载器,如requirejs
、webpack
、browserify
等systemjs
。即遵循 UMD 模式的库将被所有主要模块系统(AMD
、CommonJS
、ES6
和Vanilla JS
)识别。
这就是 CDN 中所有库的工作方式。
现在,即使您也必须遵循相同的 ieUMD
模式。由于您的图书馆已打开angular2
,我建议您选择ES6
,Angular2
和Webpack
。
您必须设置这些配置才能获取 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
},
Run Code Online (Sandbox Code Playgroud)
一旦你的 webpack 输出包准备好了(umd 模块),那么任何用户都可以将你的库注入到索引页中并开始使用你的 angular2 组件,无论他们使用什么脚本加载器/模块系统。
问:我们库的使用者如何将这个 umd 包包含在他们的 Angular 2 应用程序中?
答:由于您的库将是 UMD 模块,因此用户可以根据他们在应用程序中使用的脚本加载器/模块系统来包含该库。
例如。普通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>
Run Code Online (Sandbox Code Playgroud)
需要JS(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>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
然后您可以像往常一样导入您的库。
网页包:
在索引.html 中
在 webpack.config.js 中
{
externals: {
// require("your_lib") is external and available
// on the global var Your_Lib
"your_lib": "Your_Lib"
}
}
Run Code Online (Sandbox Code Playgroud)
Your_Lib
您的图书馆将在全球范围内可用。
归档时间: |
|
查看次数: |
497 次 |
最近记录: |