Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 412
Jimmy Ho Avatar asked Aug 26 '16 02:08

Jimmy Ho


2 Answers

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

like image 134
Jorawar Singh Avatar answered Nov 20 '22 19:11

Jorawar Singh


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?

like image 36
Jimmy Ho Avatar answered Nov 20 '22 19:11

Jimmy Ho