Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate TypeScript WebPack ts-loader with Angular2 @View styles?

I'm using Angular2 + WebPack + Typescript 1.7 stack + SASS + CommonJs.

I have webpack SASS loader configured to watch for scss files with "style!css!sass" loaders.

In my component I have @View decorator which contains styles or styleUrls parameters which can be used to pass inline styles or style url for this component.

In case I'll specify one of those @View parameters Angular2 automatically will load specified css files or (or will inline css) and that works for me.

But in case I'll use sass-loader + require() that will enable me to compile scss to css and built-in it to my js file (i'm using ts-loader and all my scripts merged into app.js).

So I can use stylesUrl to automatically preload css file by Angular2.

@View({ stylesUrl: 'my.css'}) export class Component{}

Or I can use require('*.scss') to merge css into my app.js

require('styles/my.scss');
@View({}) export class Component{}

What is the better approach for this, i mean Angular2 way?

Also I can pre-build some common.css from all scss files and simply avoid specifying any styles for component. And there simply will be 1 common.css + common.css.map file (for debugging) included in index.html

P.S. about the last approach (merge all css files)

//webpack.config.js
loaders: [
        {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract('style', ['css?sourceMap', 'sass?sourceMap']),
            include: path.join(__dirname, 'src', 'styles'),
        }
...
    plugins: [
    new ExtractTextPlugin("assets/path/styles.css?[hash]-[chunkhash]-[contenthash]-[name]", {
        disable: false,
        allChunks: true
    })


//index.html
<link rel="stylesheet" href="assets/path/styles.css" />

So now I have CDN vendor links to css. And all my custom css (written in scss) is merged to 1 file styles.css, which loaded once for all components.

This approach is sourceMap enabled. But it's a little bit tricky to clarify which scss file to modify in debug.. And also there is no any information in Angular @View declaration

like image 204
deeptowncitizen Avatar asked Dec 13 '15 14:12

deeptowncitizen


1 Answers

well I didn't quite understand the question or questions, but I will try to answer what I understood. So for me I think that neither of the 2 ways you specified is the best one. what I use is :

@Component({
 selector: 'message',
 template: '<p class = {{class}}> whatever html </p>',
 styles: [ require('./style.scss')],
 })

export class Comp{}

so by including the style sheet like that I gained 2 things:

  1. using sass and inputting it directly to my code
  2. The ability to use the view encapsulations of Angular 2
like image 128
Mostafa Fateen Avatar answered Sep 22 '22 16:09

Mostafa Fateen