I'm trying to pass parameters to my application. I found this solution which seems to have worked for people. The problem is I am using angular-cli to set up/build and ever since ~beta.14 it uses webpack instead of SystemJS.
My main.ts looks like this:
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);
}
but I'm not sure how to access this function from index.html.
My dist/index.html looks like this:
<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>
My question is, how do I call the function to pass my data in, like is done in the other post:
<script>
System.import('app').then(module => module.main('This is RIGHT'),
console.error.bind(console)
);
</script>
With webpack you can achive it by using output.library option within your webpack.config.js
Step 1
To configure it you need to change your config like:
output: {
...
library: '[name]'
},
where name
will be replaced with names of your entry's points.
This way your module will expose to global scope (window). For the main
entry it might look as shown below:
Step 2
Entry main.js
export function run(appLocalized: any) {
platformBrowserDynamic([{provide: 'AppLocalized', useValue: appLocalized }])
.bootstrapModule(AppModule);
}
Note: export
is necessarily
Step 3
Use it in your
index.html
// after all your bundles files
<script>
main.run('Passing server parameters to ngModule with Angular 2 and webpack');
</script>
For HtmlWebpackPlugin it might look like:
<% 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
}),
Alternative way is just define window property:
window["run"] = function(appLocalized: any) {
platformBrowserDynamic([{provide: 'AppLocalized', useValue: appLocalized }])
.bootstrapModule(AppModule);
}
then in your html
<script>
run('Passing server parameters to ngModule with Angular 2 and webpack');
</script>
Hope it helps you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With