V
V
Valentine2016-03-18 18:10:54
JavaScript
Valentine, 2016-03-18 18:10:54

How to set up Angular2+Webpack asynchronous routing?

Recently started working with webpacko. And still I can not teach him to accept my asynchronous routing. There is a working example in the standard build:

@RouteConfig([
  { path: '/',      name: 'Index', component: Home, useAsDefault: true },
  { path: '/home',  name: 'Home',  component: Home },
  // Async load a component using Webpack's require with es6-promise-loader and webpack `require`
  { path: '/about', name: 'About', loader: () => require('es6-promise!./about/about')('About') },
])

about.ts
import {Component} from 'angular2/core';

console.log('`About` component loaded asynchronously');

@Component({
  selector: 'about',
  template: `<h1>Bla-bla-bla</h1>`
})
export class About {
  constructor() {

  }

  ngOnInit() {
    console.log('hello `About` component');
  }

}

Even just me names, ie class name, it doesn't want to work. I also do not understand the meaning:
require('es6-promise!./about/about')('About') It does not call each other, the arguments are not substituted anywhere, what kind of miracle is this?
I will be glad for your help! As it turned out, for normal work with Angular 2, webpack needs to be configured slightly ... almost through every action, what kind of problem pops up.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-03-18
@Waynes

require('es6-promise!./about/about')('About')
Let's try to figure it out. We go to the documentation for the webpack .
Those. this construct require('es6-promise!./about/about')is a call to load the module using an overridden loader, and not just a loader that is registered in the webpack.config.js of this assembly

loaders: [
  // See: https://github.com/s-panferov/awesome-typescript-loader
  {test: /\.ts$/, loader: 'awesome-typescript-loader', exclude: [/\.(spec|e2e)\.ts$/]},

We go to the sources of es6-promise-loader , which is just one of the devDependencies of the assembly. There you can laugh a little at the comments).
Let's see what's here, yeah - this is a pitch loader that wraps es6-promise . And inside the ensure method from the webpack , which allows you to separate the chunk and load it dynamically. As a result, approximately such a module is obtained (I cut the paths a little)
I.e. require('es6-promise!./about/about') roughly turns into a function with a namespace parameter . And in general, when it comes time to keep your promise and return the module, the following expression will work
Require will return to us just our exports object, which we return in about.ts
to the property of the object by namespace . That is why there is ' About '.
If you write about , then you will not see
ngOnInit() {
  console.log('hello `About` component');
}
from component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question