What are the advantages of importing CSS files from JS source code with webpack, rather than building CSS in isolation as traditionally done?

If you're looking for information on how to load CSS with webpack, check out the documentation here: https://webpack.js.org/guides/asset-management/#loading-css1

The webpack documentation suggests importing CSS files from JavaScript code and using extract-text-webpack-plugin to extract the CSS.

--> Why does webpack recommend importing CSS files from JS code instead of building CSS in isolation like traditional methods?

By not importing CSS from JavaScript, it means that the webpack configuration for CSS doesn't have a ".js" extension and instead parses CSS/SCSS files directly.

There are advantages to not importing CSS from JavaScript:

  1. (objective fact). If you only need to build CSS, it is faster as the bundler doesn't have to parse JavaScript source code. Additionally, parallel-webpack allows for simultaneous bundling of CSS and JavaScript.

  2. (subjective, based on tradition, but important nonetheless). Building SASS in isolation has been the traditional approach for years, resulting in better HTML semantics and maintainability. Importing CSS from JS is virtual and may lead to neglecting the separate CSS bundle generated.

  3. (objective fact) By separating the config files for CSS and Javascript, clarity can be improved.

Answer №1

With over 15 years of experience, I consider myself more of a traditionalist in this field. However, I must admit that the modern approach to separating concerns is far superior to the conventional method.

In the past, we used to compartmentalize layout, styling, and functionality (html, css, js) separately. While this made file organization easy, it often led to difficulties in locating specific code related to certain features. For example, a button could be spread across different files such as /src/shop-front.html, /src/css/shop-front.css, and /src/js/shop-front.js.

The new paradigm involves segregating concerns by components. Now, components like 'shop-front' are constructed from /src/components/button/ where all relevant files reside. This includes the javascript file incorporating the css style sheets.

The beauty of this approach is evident when you decide to replace 'button' with 'fancy-button'. Simply changing the import statement from import button from 'button' to

import button from 'fancy-button'
automatically removes the old code without requiring manual adjustments at various locations.

Regarding the points raised:

  1. While node-sass may be faster, the marginal difference compared to webpack is negligible. The enhanced developer experience offered by the latter justifies any minimal time discrepancy.

  2. Concerning the css/sass structure, there is no change in how it's built by requiring it from a javascript file. Whether using css modules is optional, I prefer sticking to sass and applying class names conventionally.

  3. Although webpack configuration allows splitting the js config from the css config, the small size of the setup makes it unnecessary to complicate things further.

The simplicity and logic of my folder structure can be observed here:

This represents a basic configuration for importing scss files:

const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { SRC, DIST } = require('./src/config/paths');

module.exports = {
  devtool: 'source-map',
  cache: true,
  context: SRC,
  entry: {
    app: [`${SRC}/client-entry.js`]
  },
  output: {
    path: DIST,
    filename: '[name]-[chunkhash].js',
    publicPath: '/'
  },
  plugins: [
    new ExtractTextPlugin('[name]-[contenthash].css'),
  ],
  resolve: {
    modules: ['node_modules', SRC],
    extensions: ['.js', '.jsx', '.scss']
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: [/src/],
        loader: 'babel-loader',
        options: {
          cacheDirectory: true
        }
      },
      {
        test: /\.s?css$/,
        include: [/src/],
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'postcss-loader', 'sass-loader']
        })
      }
    ]
  }
};

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

Three image resources combined to create a unique border design in CSS

I am currently working on designing a webpage and am in need of creating a background border. I have access to three image resources for this task: one for the left side, another for the top, and the third for the right side. My struggle lies in finding s ...

What exactly is the function of $fix-mqs within the IE Sass mixins created by Jake Archibald?

I'm really struggling to understand the purpose behind using $fix-mqs in the mentioned link: Although I can grasp how the rest of the mixin functions, this particular part has me stumped. In a project where I've utilized this pattern, everything ...

I am having trouble getting bootstrap-icons to work in my Angular project and I'm eager to figure it out

I am having trouble incorporating bootstrap-icons into my angular project. Despite running the npm i bootstrap-icons command, I am unable to successfully add icons using icon fonts on my webpage. As a temporary solution, I have added the bootstrap icon CD ...

Aligning a DIV using javascript

Hey everyone, I'm encountering an issue with the JavaScript on my website. I'm struggling to center the div in order to properly display the image I click on. It seems to work fine on the second attempt, but on initial click, the div always appea ...

Ways to create a fading effect for a div container

As I delve into learning Rails, I've been immersed in a Rails web app where there is an enticing "Order" button that triggers a response saying: "Thank you for ordering". This message is displayed using the flash action. To enhance user experience, my ...

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

Leap over in a similar fashion to the provided demonstration

In my attempt to create a unique project, I have created this CodePen example. The goal is to have one ball on the circle that remains in a fixed position, while another rotating main ball must avoid touching it at all costs. Points are awarded for success ...

Trouble encountered in aligning two DIVs in a horizontal position

I have been through numerous discussions on the same problem, but none of the solutions seem to work in my case. I am currently working on a section of my website that has 3 small boxes, each containing an image on top and text below. The issue arises when ...

The inner panel height does not extend to 100% when there is overflow

When pressing the submit button on a panel containing components, an overlay appears but does not cover the entire parent panel if scrolled to the bottom. Additionally, I want the spinner to always be centered, whether scrolling or not. I've tried usi ...

Height of the image is being boosted while the width remains consistent

When working on a responsive page layout, I encountered an issue with increasing the height of an image while keeping the width constant. Modifying the width of the image reflects changes, but adjusting the height does not seem to make any difference. I t ...

Bootstrap allows you to create a responsive grid

I need assistance with making my bootstrap grid responsive for multiple input search filters on mobile devices. Currently, the layout is not showing correctly on mobile phones. On desktop, the output looks fine: https://i.stack.imgur.com/bKPUv.png Howev ...

What is the process for applying this specific style to a certain element?

Here is an example of an element in an Angular2 app: <div class="ticket-card" [ngStyle]="{'background': 'url(' + ticketPath + ')' , 'background-size': 'cover'}"> I would like to enhance the style b ...

As I resize my browser window, I notice that my menu button starts to shift upwards along the

I recently created a menu button that looks great, but I noticed that when I shrink the browser window, it starts to move slightly upwards. It's really annoying and I can't figure out why this is happening. Can someone please help me troubleshoot ...

Is it possible to incorporate varied icon images for every item in an unordered list?

While I'm not an CSS expert, I do have a decent understanding of it. My current project involves creating an unordered list with unique icons for each item, along with changing the background color upon hover. I wonder if there's a way to achiev ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

What is the method for compressing text in CSS?

I'm curious about how to condense my text so it doesn't extend beyond the page. Any ideas on how to achieve this? Issue: Solution: .Subheading{ text-align:center; font-family: 'Mukta', sans-serif; margin-top:70px; m ...

Two scenarios for tag class and just class are considered in this discussion

FOUND THE SOLUTION. Sending a huge shoutout to @JHeth and @Marko Vucurovic for their invaluable help! This query may seem lengthy, but the concept is straightforward. Let's break it down into 2 scenarios: Scenario I <html> <head><titl ...

Troubleshooting issue with CSS code for table scrolling functionality

I have created an HTML page with a table that gets data from a database. I am trying to limit the size of the table by placing it inside a div like this: <div id="scrollablebody"> <table class="clientTable"> <thead> <tr ...

Shadow box with arrow/bubble element using CSS

I am looking to add a box shadow around the outline of the bubble below. <div class=speech-bubble-dark></div> .speech-bubble-dark { position: absolute; background: #fff; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2); border-radius: 0.4em; ...

Tips on formatting text as bold or italic when tweeting from my website to our Twitter account

Currently, I am utilizing the Twitter OAuth library in conjunction with PHP to publish a tweet from my website directly to my Twitter account. My main objective is to highlight some text while posting, however, I have not been successful in identifying t ...