Angular2 + Webpack我应该如何使用templateUrl输出html文件?

Jim*_* Ho 5 webpack angular

我编写了一个组件,它使用templateUrl来包含一个html文件

/*component*/
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
/*html*/
<h1>My First Angular 2 App</h1>
Run Code Online (Sandbox Code Playgroud)

webpack配置就好

  {
    test: /\.ts$/,
    loaders: [
      'awesome-typescript-loader'
    ],
    exclude: [/node_modules/,/\.(spec|e2e)\.ts$/]
  },{
    test: /\.html$/,
    loader: 'raw-loader',
    exclude: [path.resolve(__dirname, "index.html")]
  }

new HtmlWebpackPlugin({ template: 'index.html' })
Run Code Online (Sandbox Code Playgroud)

输出js文件应该包含html,但它没有

这是我在github中的代码 https://github.com/jiaming0708/ng2-webpack

Jor*_*ngh 6

您可以使用angular2-template-loader,因此您无需编写要求它将为您完成该任务,您可以继续编写简单的语法

 templateUrl: './app.component.html'
Run Code Online (Sandbox Code Playgroud)

代替

template: require('./my-component.html')
Run Code Online (Sandbox Code Playgroud)

它是如何工作的

angular2-template-loader在Angular 2 Component元数据中搜索templateUrl和styleUrls声明,并用相应的require语句替换路径.

如何在我的项目中添加它

npm install angular2-template-loader --save-dev
Run Code Online (Sandbox Code Playgroud)

webpack.config中的小变化

loaders: ['awesome-typescript-loader', 'angular2-template-loader']
Run Code Online (Sandbox Code Playgroud)

使用html-loader而不是raw loader

 {test: /\.html$/, loader: 'html'}
Run Code Online (Sandbox Code Playgroud)

学到更多


Jim*_* Ho 5

我发现angular2-webpack-starter没有使用require并使用templateUrl.

配置

  {
    test: /\.ts$/,
    loaders: [
      'awesome-typescript-loader',
      'angular2-template-loader',
      '@angularclass/hmr-loader'
    ],
    exclude: [/\.(spec|e2e)\.ts$/]
  },
  {
    test: /\.html$/,
    loader: 'raw-loader',
    exclude: [helpers.root('src/index.html')]
  }
Run Code Online (Sandbox Code Playgroud)

零件

  templateUrl: './home.template.html'
Run Code Online (Sandbox Code Playgroud)

他们为什么能这样做?