Jimmy Ho
Jimmy Ho

Reputation: 676

Angular2+Webpack how should I output html file with templateUrl?

I write a component that it uses templateUrl to include a html file

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

webpack config like

  {
    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' })

output js file should including the html, but it doesn't have

it's my code in github https://github.com/jiaming0708/ng2-webpack

Upvotes: 5

Views: 7552

Answers (3)

Jimmy Ho
Jimmy Ho

Reputation: 676

I discovered angular2-webpack-starter that it did not using require and using templateUrl.

config

  {
    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')]
  }

component

  templateUrl: './home.template.html'

Why they can do it?

Upvotes: 5

Jorawar Singh
Jorawar Singh

Reputation: 7621

You can use a angular2-template-loader so you don't need to write require it will do the that job for you and you can keep writing simple syntax like

 templateUrl: './app.component.html'

instead of

template: require('./my-component.html')

How does it work

The angular2-template-loader searches for templateUrl and styleUrls declarations inside of the Angular 2 Component metadata and replaces the paths with the corresponding require statement.

How to add it in my project

npm install angular2-template-loader --save-dev

Small change in webpack.config

loaders: ['awesome-typescript-loader', 'angular2-template-loader']

Use html-loader instead of raw loader

 {test: /\.html$/, loader: 'html'}

Learn more

Upvotes: 6

RJo
RJo

Reputation: 16291

If you want to include the html in the JS bundle, use the raw loader, just as you did. However, webpack does not recognize the file for you, if you don't require it. Instead of using templateUrl, use template:

@Component({
  selector: 'my-component',
  template: require('./my-component.html')
})

If you want a separate html file in the output, use the file-loader and templateUrl

Upvotes: 0

Related Questions