简体   繁体   中英

Webpack 2: SASS themes with Angular

Webpack 2.2.1, Angular 2.4.7.

I'm creating a site that has multiple themes using SASS, but haven't been able to get Webpack to create individual CSS files for each theme. ExtractTextPlugin shows promise because it creates a separate CSS file for each entry point, but not the theme specific ones I need. Is there any way to have each ThemeX.scss be output as something like /themes/ThemeX.css? Note that the themes are named differently, but I'm using names like ThemeA.css for the sake of brevity. They're actually Sales.css, Engineers.css, etc.

Example directory structure for the themes is:

src/assets/styles/themes/ThemeA/ThemeA.scss 
src/assets/styles/themes/ThemeB/ThemeB.scss

Webpack config

const extractThemePlugin = new ExtractTextPlugin("themes/[name].css");

{
    test: /\.scss$/,
    include: helpers.root('src/assets/styles/themes'),
    use: extractThemePlugin.extract({
        fallback: "style-loader",
        use: ["css-loader", "sass-loader"]
    })
}

plugins: [ extractThemePlugin, ...and others ]

Things I've tried

1: Setting each of the ThemeX.scss files as an entry point:

entry: {               
   'main': './src/main.browser.ts',
   'themeA': helpers.root('src/assets/styles/themes/themeA/themeA.scss'),
   'themeB': helpers.root('src/assets/styles/themes/themeB/themeB.scss')
}

which creates the individual files, but each of them is a copy of the other, so ThemeA.css, ThemeB.css and ThemeC.css all contain the contents of ThemeA.css.

2: Importing each of the themes in the root app.module.ts. This just bundles the files into a single CSS file.

3: Creating an ExtractTextPlugin instance for each theme. This also creates files with duplicated content, similar to #1.

const extractThemeAPlugin = new ExtractTextPlugin("themes/themeA.css");
const extractThemeBPlugin = new ExtractTextPlugin("themes/themeB.css");

You can use multiple regex match in config section of your webpack instead of just having a single extracttext entry:

First put this at the top of webpack config:

let extractTheme1 = new ExtractTextPlugin('theme1.css');
let extractTheme2 = new ExtractTextPlugin('theme2.css');

Then in config:

{
    test: /\.scss$/i,
    exclude: [
        /theme2\.scss$/i
    ],
    use: [extractTheme1.extract('css-loader'),
        'css-loader',
        'sass-loader'
    ]
},

// SCSS Loader
{
    test: /theme2\.scss$/i,
    use: [extractTheme2.extract('css-loader'),
        'css-loader',
        'sass-loader'
    ]
},

And in plugin section:

plugins: [
   ...
   extractTheme1,
   extractTheme2
   ...
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM