路由不适用于捆绑(webpack)Angular 2项目

时间:2017-08-14 17:26:48

标签: javascript angular typescript webpack

我有一个带有2个组件(AppComponent和tester)的简单角度应用程序,它们被webpacked到一个app.bundle.js文件中。我的问题是,一旦捆绑应用程序,路由不再有效。我尝试了一些在线看到的不同方法让这个工作没有运气,任何人都可以帮忙吗? 我已经看到通过模块提到捆绑和路由,但我宁愿将整个角度项目保留为单个文件,如果可能的话

<!DOCTYPE html>
<html>
  <head>
    <title>Routing webpack test</title>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="slate.css">
  </head>
  <my-app>Loading...</my-app>
  <body>
  <script type="text/javascript" src="app.bundle.js"></script>
  </body>
</html>

app.component.ts

import { Component, Input, Output } from '@angular/core';
import { Route } from "@angular/router";
@Component({
  selector: 'my-app',
  template: `<h1>Hello world</h1>`
})
export class AppComponent  {}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app/app.component'
import { tester } from './app/test.component';

const appRoutes: Routes = [
  {
    path: '',
    component: AppComponent
  },
  {
    path: 'test',
    component: tester
  },
  {
    path: 'myapp',
    component: AppComponent
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes,{ enableTracing: true }), 
    BrowserModule, FormsModule],
  exports: [RouterModule],
  declarations: [AppComponent, tester ],
  bootstrap: [AppComponent]
})
export class AppModule { }

webpack.config.js:

var webpack = require('webpack');
var HtmlWebpack = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CompressionPlugin = require('compression-webpack-plugin');

module.exports = {

  entry: [
    __dirname + '/src/main.ts'
  ],
  output: {
    path: __dirname + '/src/dist',
    filename: 'app.bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['ts-loader', 'angular2-template-loader', 'angular2-router-    loader']
      },

    ]
  },
  resolve: {
    extensions: ['.js', '.ts']
  },
  plugins: [
    new HtmlWebpack({
      template: './src/index.html'
    }),
    new CopyWebpackPlugin([
      { from: './src/slate.css' }
    ]),
    new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify('')
    }
  }),
  new webpack.optimize.AggressiveMergingPlugin(),
  new CompressionPlugin({
     asset: "[path].gz[query]",
     algorithm: "gzip",
     test: /\.js$|\.css$|\.html$/,
     threshold: 10240,
     minRatio: 0.8
   }),
  new webpack.ContextReplacementPlugin(
    /angular(\\|\/)core(\\|\/)@angular/,
    './src',
    {}
  ),
  ],
};

1 个答案:

答案 0 :(得分:1)

模板需要一个占位符(routeroutlet)来加载路由器组件。 我想你错过了

<router-outlet> </router-outlet>