Utilize CSS (Sass) from various modules in your project

Planning to create a repository for npm, similar to react-leaflet and react-d3, that will consist of various modules. Developers can include these modules from the npm package using require/import. For example:

import { ModuleOne, ModuleTwo } from 'myNpmPackage`;

The challenge is packaging CSS along with each module, compiled from Sass files in each one.

Considering a folder structure like this for myNpmPackage:

├── src
│   ├── ModuleOne
│   │   ├── index.js
│   │   ├── style.scss
│   ├── ModuleTwo
│   │   ├── index.js
│   │   ├── style.scss
├── package.json

How can we publish these .scss files (compiled into

.css</code) without requiring consumers to manually include / <code>@import
/ link rel="stylesheet" the CSS?

Utilizing gulp and browserify pipeline is preferred.


UPDATE: Discovered parcelify offers partial solution. Adding the following configuration to myNpmPackage/package.json:

"style": "src/**/*.scss",
"transforms": [
  "sass-css-stream"
]

Including parcelify in dependencies so it's installed with myNpmPackage.

Consumers need to update their gulpfile with:

parcelify(b, {
    bundles: {
        style: './build/modules.css'
    }
});

parcelify uses the glob in myNpmPackage/package.json to bundle all .scss files into ./build/modules.css.

This solution has drawbacks:

  1. All CSS files are included in consumer application build, even if not all modules are used;
  2. Requires manual addition of code to gulpfile by consumer developers.

Answer №1

Check out this Webpack configuration that fulfills all your requirements:

  • Only CSS modules that are imported are included in the final build (ModuleThree, for example, is excluded).
  • No need to modify any existing gulpfile.js or *.config.js; each module simply requires its own stylesheets like any other dependency.

Bonus Tip: ModuleTwo demonstrates how to dynamically load CSS and also includes a background image, treated as a regular dependency.

Important: While I didn't use ES2015 syntax in this demo, you have the option of incorporating it using babel-loader.

Answer №2

The way you handle your SCSS to CSS conversion depends on your unique development pipeline. One approach is to render all your SCSS into CSS when building your app. If you end up with a single CSS file containing all styles, you can easily include it in a JavaScript file using various methods provided by tools like the gulp ecosystem and plugins such as this one.

function addStyleString(str) {
    var node = document.createElement('style');
    node.innerHTML = str;
    document.body.appendChild(node);
}

addStyleString('/* CSS File 1 */');

You can set this up in your gulp pipeline like so:

var gfi = require("gulp-file-insert");

gulp.src('./sample.js')
  .pipe(gfi({
    "/* CSS File 1 */": "path/to/main.css"
  }))
  .pipe(gulp.dest('./dist/'));

If you're interested, you can check out this reference: Inject CSS stylesheet as string using Javascript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Contrasting characteristics of a node.js server built with http.createServer versus one created with express

Could you explain the distinction between setting up a server with the http module versus configuring a server with the express framework in Node.js? Appreciate it. ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

Leveraging the Firebase email trigger extension with JavaScript

Recently, I integrated the email trigger extension for Firebase. Below is the function I am using: firestore .collection("profiledata") .doc(user.uid) .update({ accountStatus: "active", }) .then(() => { // At this p ...

Is there a way to use Laravel to send an asynchronous post request for managing likes?

Currently, I am managing likes in the following way: class LikeController extends Controller { public function like(Post $post) { $attributes = [ ['user_id', '=', auth()->user()-&g ...

Using the typeof operator to test a Typescript array being passed as an object

I have a puzzling query about this particular code snippet. It goes like this: export function parseSomething(someList: string[]): string[] { someList.forEach((someField: string) => { console.log(typeof someField) }) Despite passing a s ...

The state returned by React Redux does not meet the expected results

I recently implemented a like function on the backend using Node and MongoDB. This function successfully returns the post with an updated likes counter, which I tested using Postman. The post object contains properties such as likes, _id, by, createdAt, an ...

The Highcharts Angular Chart fails to update after the renderer.button event is triggered

Within the chart interface, you'll find two unique buttons designed to facilitate the updating of the series and redrawing of the chart based on user preference. One allows for toggling views by percentage, while the other does so by count. When the c ...

Having difficulty maintaining the consistent size of the MathJax math font in relation to the surrounding text

Issue I am currently using MathJax to display mathematical equations on my webpage: https://i.sstatic.net/EfvVq.png The problem I am facing is that I want the math font to appear larger than the surrounding text, as depicted in the image above. However, ...

Setting the variable to global does not apply styling to the element

Looking for help with styling an element created using document.createElement("img")? let fireball; //global variable fireball = document.createElement("img") //variable on local fireballArray.push(someFunction(fireball, { src: "img.png&qu ...

The item I possess fails to catch the light in Three.js

I have a situation where CubeGeometry based meshes in a three.js scene are reflecting the PointLight I'm using globally, except for one particular mesh. This specific mesh was created "by hand" using just THREE.Geometry (adding vertices and faces thro ...

Implement Offcanvas feature with Bootstrap 3 Navbar set to Fixed Top position

I am in the process of creating a website that will feature a large menu. However, I am not a fan of the collapsed menu that comes with BS3. Instead, I would like to implement a drawer or off-canvas menu similar to the one showcased in BS3's offcanvas ...

Which alternative function can I use instead of onchange without having to modify the slider beforehand in order for it to function properly?

Check out my website: alainbruno.nl/form.html to see the "Race" form and the "Age" slider. I've noticed that the minimum and maximum values of the Age slider only update correctly when you first use the slider before selecting a different race. Any id ...

Why is my nested React Router component failing to load upon page refresh?

Lately, I have been delving into learning react and for the past few weeks. However, I've encountered an issue where when I try to reload the page using the browser's reload button, instead of reloading the component, it simply disappears (turnin ...

When using npm/gulp, it may sometimes fetch numerous modules that are not listed in the package.json file

I'm having a hard time grasping why, in every instructional video I watch, simply running "npm install" or "gulp install" results in downloading over 150 separate node modules that aren't even listed in my package.json file. These additional modu ...

Component not appearing in React Router v4

Currently, my web app is facing an issue where it does not navigate to the component when accessing the parameters. Specifically, it fails to reach the Battle component. This is how the navigation is set up: import React from 'react'; impor ...

A step-by-step guide on transferring Data URI from canvas to Google Sheet using the fetch method

I am trying to send an image as base64 code to a Google sheet using fetch. However, I am encountering an error that says "data_sent is not defined" when I run my code. I need help identifying the problem and finding a solution to fix it. For reference, & ...

Creating a Dynamic Scrolling Effect in React JS: Rendering a New Component as You Scroll

I am interested in replicating the layout of the home page found at . As you scroll down the page, new components are loaded sequentially. My goal is to stack these components one after another like this: <Background Media-1 /> <Background Media ...

Javascript experiencing a malfunction

Having some trouble with setting up proper checks for duplicate user creation in a simple signup process. Can't seem to get the sequence right: route: app.post('/user/new', user.create); user.create: exports.create = function(req, res) { ...

Ensure that each image is not affected in jQuery

How can I ensure that when a user moves the jQuery Slider, only the images related to that slider are affected? I've attempted using: $(this).closest('img.down') and $(this).siblings('img.down') $("#slider").slider({ value:50, ...

When state updates in React, the component will rerender without affecting its style

There seems to be a minor oversight on my part. The issue arises in the parent component where I maintain a state of selected items, which are added from the child component. The background color of the child component changes when an item is selected. Ad ...