加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用Angular 2和webpack将服务器参数传递给ngModule

发布时间:2020-12-17 10:25:47 所属栏目:安全 来源:网络整理
导读:我正在尝试将参数传递给我的应用程序.我发现 this solution似乎对人有用.问题是我正在使用angular-cli来设置/构建,从那以后~β.14它使用webpack而不是SystemJS. 我的main.ts看起来像这样: import './polyfills.ts';import { platformBrowserDynamic } from
我正在尝试将参数传递给我的应用程序.我发现 this solution似乎对人有用.问题是我正在使用angular-cli来设置/构建,从那以后~β.14它使用webpack而不是SystemJS.

我的main.ts看起来像这样:

import './polyfills.ts';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';

if (environment.production) {
  enableProdMode();
}

export function main(appLocalized: any) {
  platformBrowserDynamic([{provide: 'AppLocalized',useValue: appLocalized }])
    .bootstrapModule(AppModule);
}

但我不知道如何从index.html访问此功能.

我的dist / index.html看起来像这样:

<body>
  <app-root>Loading...</app-root>
<script type="text/javascript" src="inline.js"></script><script type="text/javascript" src="styles.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script></body>

我的问题是,如何调用函数来传递我的数据,就像在另一篇文章中所做的那样:

<script>
  System.import('app').then(module =>   module.main('This is RIGHT'),console.error.bind(console)
            );
</script>
使用webpack,您可以在webpack.config.js中使用 output.library选项来实现它

步骤1

要配置它,您需要更改您的配置,如:

output: {
  ...
  library: '[name]'
},

其中name将替换为您的条目点的名称.

这样,您的模块将公开到全局范围(窗口).对于主条目,它可能如下所示:

第2步

进入main.js

export function run(appLocalized: any) {
  platformBrowserDynamic([{provide: 'AppLocalized',useValue: appLocalized }])
    .bootstrapModule(AppModule);
}

注意:出口必然

第3步

在你的使用中使用它

的index.html

// after all your bundles files
<script>
  main.run('Passing server parameters to ngModule with Angular 2 and webpack');
</script>

对于HtmlWebpackPlugin,它可能看起来像:

<% for (var chunk in htmlWebpackPlugin.files.chunks) { %>
<script src="<%=htmlWebpackPlugin.files.chunks[chunk].entry %>"></script>
<% } %>

<script>
  main.run('Passing server parameters to ngModule with Angular 2 and webpack');
</script>

webpack.config.js

new HtmlWebpackPlugin({
   template: 'src/index.html',inject: false <== don't forget this line
 }),

另一种方法是定义窗口属性:

window["run"] = function(appLocalized: any) {
  platformBrowserDynamic([{provide: 'AppLocalized',useValue: appLocalized }])
    .bootstrapModule(AppModule);
}

然后在你的HTML中

<script>
    run('Passing server parameters to ngModule with Angular 2 and webpack');
</script>

希望它能帮到你!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读