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:

https://i.sstatic.net/ziNGS.png

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

What is the best way to ensure that a div containing lengthy text wraps to the next line as if it were only text overflow?

Is there a way to make a div or span within another div act as text, causing overflow to shift to the next line? I'm unsure of which CSS properties would achieve this effect. I've attempted using overflow-wrap: break-word; word-break: break-al ...

issue arising where the table's border is not displaying

I'm confused about why the border of the first tbody tr's td is not visible. https://i.stack.imgur.com/Fwlv7.png I can't see any reason why the border is not showing up. Here's what I've figured out: If the natural height of th ...

Arranging DIV elements into rows and columns within a table

After working all night to fix a problem, my goal is to create this timetable: https://i.sstatic.net/dAt1J.png Specifically, I'm struggling to find a solution for rows 5, 6, and 7 in the first column. The image is from a program that only runs in IE ...

Style applied directly to .col elements

I want to customize the styling of the .col elements on a single page without affecting other pages. I've tried adding the following code snippet to my CSS file: .col { border: 1px solid #7851A9; } However, this also styles the element ...

Adjust the dimensions of the canvas without disrupting the existing artwork

I am currently working on a pixel art application where I am facing an issue with saving images from the canvas. The saved image appears small and pixelated when I try to resize it. I would like to resize the image to larger dimensions, but I am unsure of ...

Creating a clickable navigation menu item with a clickable caret located on the same line

I've been developing a solution using Twitter Bootstrap to create a main navigation menu that expands upon hover on desktop, while the menu expands when clicking the caret on mobile (caret hidden on desktop). Additionally, I aimed to make the top-leve ...

How can I style the empty text in an ExtJS grid using CSS?

Is there a specific CSS class for a grid's emptyText? After inspecting the element with Firebug, all I found was: <div id="gridview-1021" class="x-component x-grid-view x-fit-item x-component-default x-unselectable" role="presentation" tabindex=" ...

When I click on any input field, button, or other controls on a webpage, the page automatically zoom

I am currently trying to troubleshoot an issue with a bootstrap theme. It seems to be working perfectly on all browsers except for ios safari browsers. Whenever I click on an input field or button, the page suddenly zooms in. It's quite frustrating. ...

HTML: Align DIV contents next to each other without any overlap

Below are three boxes displayed. Boxes 1 and 3 appear fine, but in box 2 the text content is overlapping. The issue lies with the <div> having the class .vertical_center.grade_info which has a specific margin-left of 100px, causing the overlap. I ne ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...

Ways to maintain hover functionality when the submenu is visible

My website features a simple table that displays devices and their characteristics. A condensed version of the table can be found in the link below. import "./styles.css"; import { SubMenu } from "./SubMenu"; const subMenuSlice = <S ...

The alignment of Bootstrap v4.5 checkbox is limited as it cannot be positioned horizontally or vertically when placed next to an input field

As stated in the title: Bootstrap's checkbox is having trouble aligning Horizontally or Vertically when placed next to an input. Error Displayed: https://i.sstatic.net/hNHpm.png I have experimented with various solutions, but none have provided sat ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

How can we bring in a function into a Vue component?

I'm currently facing an issue with importing a single function into my Vue component. To tackle this problem, I separated the function into its own js file: randomId.js: exports.randomId = () => //My function ... Within my Vue component, I attem ...

What is the best way to ensure a div container fills the entire height of the screen?

I am currently working on developing my very first iOS HTML5 app, which is a simple quote application. One challenge I am facing is how to set the height of my container div to match that of an iPhone screen. You can view the design I have so far on this j ...

Issue with Angular 6 Animation not showing up

Looking to incorporate an animation spinner into my Angular app Found this spinner example: https://codepen.io/z-/pen/OPzNLz spinner.component.html import { Component, OnInit } from '@angular/core'; @Component({ selecto ...

What is the best way to position my two icons next to each other in the footer of my React application?

I'm struggling with styling the footer of my react portfolio project. I specifically want to include Github and LinkedIn icons side-by-side at the bottom of the screen, but currently, they are stacked vertically in the middle of the page with too much ...

Tips on incorporating background color into HTML emails dispatched via PHP mail()

Struggling to add a background color to my HTML email. I've attempted various methods: Inserting <script> tags with CSS code inside Adding bgcolor in body tags Using a CSS style sheet All to no avail. I suspect it could be the email provi ...

Customize the appearance of Angular components by altering their color schemes

When working on my project, I often utilize pre-made Angular components. However, some of these components come with colors that do not align with the overall aesthetic of my project (refer to image above). To rectify this issue, I am looking to replace t ...

Preventing Paste Function in Electron Windows

Currently, I am utilizing Electron and attempting to prevent users from pasting into editable content. While paste and match style remains enabled, the functionality is flawless on Mac devices. However, there seems to be an issue on Windows where regular ...