ben tedder : code things

Creating separate .scss and .js entry paths in Webpack

I'm currently creating a component library / design system in Angular 4 that needs to be consumed by other Angular 4 projects. In my use case I need to bundle up the .js file that gets imported as a module, and I want to separately bundle the scss file to generate a bundle.min.css file to @import into my scss files in other projects. Here's how it works.

  • Install extract-text-webpack-plugin, css-loader, and sass-loader for Webpack (I'm using Webpack 2.2.1)
  • Create your webpack config (I'm just showing you the bits that matter for this specific task)

var ExtractTextPlugin = require('extract-text-webpack-plugin');

... rest of webpack config here

config.entry = { myLibrary: './src/myLibrary/index.ts', styles: './src/myLibrary/styles.scss', } config.output.filename = 'myLibrary/[name].js';

... other ts config things here

config.module.rules.push( { test: /.scss$/, loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader']) } ) config.plugins.push( new ExtractTextPlugin({ filename: 'myLibrary/myLibrary.bundle.css', allChunks: true, }) )

... rest of webpack config here

Let's walk through what's happening.

First, we're declaring two entry points, a SCSS file and a ts file.

Next, we're setting the dynamic [name] field. Although as I write this, it seems that the ExtractTextPlugin may be doing that for us with the .scss file.

Finally, we're going to assume you know what you're doing with your Angular index.ts file and move on to the .scss file. We need to set a rule that sends the .scss file through the Extract Text plugin. It's pretty basic, as long as your sass compiles you should be fine.

Noteworthy: This process actually produces three files. It produces an additional styles.js file, assuming you want to inject your css as a webpack bundle. I'm not going to declare what you should do with it...but I just delete it and import the .scss file into the app that is consuming this library.

Hopefully soon I'll post some more about how I'm building a design system / component library using Angular 4 and Webpack. Let me get it a bit more complete first...