Combine and compress all less files using Webpack without the need for manual import

I have a collection of approximately 20 individual less files that I am looking to combine into one file using Webpack and save it in my /dist directory. Below is my current Webpack configuration file:

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const bundleOutputDir = './wwwroot/dist';


module.exports = (env) => {
    const isDevBuild = !(env && env.prod);
    return [{
        stats: { modules: false },
        entry: { 'main': './ClientApp/boot.ts' },
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            path: path.join(__dirname, bundleOutputDir),
            filename: '[name].js',
            publicPath: '/dist/'
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
                { test: /\.html$/, use: 'raw-loader' },
                { test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader' }) },
                { test: /\.less/, use: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader') },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [
            new CheckerPlugin(),
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins specifically for development builds
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', 
                moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') 
            })
        ] : [
                // Plugins for production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new ExtractTextPlugin('site.less'),
                new ExtractTextPlugin('site.css')
            ])
    }];
};

When attempting to import each individual .less file into the boot.ts entry file, I encounter a less error indicating that the less variables I've defined are not being recognized. This led me to believe that pre-concatenation is necessary. Coming from a gulp background, any assistance on setting this up would be highly valued.

If there exists an alternative method to compile all less to css successfully without concatenation, I am open to suggestions.

Answer №1

Webpack acts as a module bundler, utilizing various module syntaxes for JavaScript (ES6, CommonJS, AMD..), CSS (@import, url), and even HTML (via src attribute) to construct the app's dependency graph before serializing it into multiple bundles.

In this scenario, encountering errors when importing *.less files indicates a lack of CSS modules. Essentially, if you are using variables from another file without properly @import-ing that file, errors will arise.

For Webpack, it is advisable to modularize all components. Thus, adding the necessary CSS modules is recommended. I faced a similar issue during a project migration from Grunt to Webpack. As a temporary fix, creating an index.less file where all less files are @import-ed (in correct order) and then importing that file in the app's entry point (e.g. boot.ts) can help resolve the issue.

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

Discover more efficient methods for utilizing generics in hierarchical objects within typescript

How can I optimize the structure of an object that contains nested objects in Typescript to minimize type repetitions? type itemType = { [key: string]: { [key: string]: { [key: string]: { [key: string]: string } }; }; }; ...

What could be causing this RangeError to constantly come up while I'm performing a basic math operation in node.js?

My program simply takes two inputs from an HTML form, parses them into text in Node, and then performs a math operation on the two. Strangely, this issue only occurs when dealing with numbers, not strings. Despite the error message indicating an invalid s ...

Iteration in Angular using ForEach Statement

Can anyone help me with executing a For loop synchronously in Angular 5? The code I have so far doesn't wait until ExcecuteAsyncCode is completed. let items = new Array<Item>(); for (let i = 0; i <= 10000; i += 1) { this.ExcecuteAsyncC ...

Within a loop featuring multiple buttons, apply a class toggle specifically to the button that is clicked on

CSS: .btn-category-list-col { background:#f4f6f9; border: 0 !important; } .btn-category-list-col:hover { background: #E2EEFC; } .btn-category-list-col button:hover { font-weight: bold; } .btn-category-list-col-click { background: #E2EE ...

What are the advantages of using the CRUD coding style with Redux?

Seeking guidance on the best coding style for a single page application regarding the use of React Redux For instance, consider a standard CRUD page where data is presented in a table with a pop-up modal form. The table's data comes from server-side ...

What is the best way to save functions that can be utilized in both Vue front-end and Node back-end environments at the same time?

As I dive into the world of Node/Express back-end and Vue.js front-end development, along with server-side rendering, I am faced with the need to create utility functions that can format textual strings. These functions need to be accessible and reusable b ...

Having trouble with querying specific items using node-mysql and JavaScript

p_info_query('SELECT * FROM ' + <table> + ' WHERE name = ' + user_name, password, client_connect.id, p_info, function(results) { I keep getting an error about an Unknown Column 'user_name' when trying to run this query. ...

Display information retrieved from a PHP request on an AngularJS webpage

I could really use some assistance upfront! I am facing issues with displaying the data retrieved from PHP on an AngularJS website. I have reviewed previous discussions on this topic, but unfortunately, none of them have proven helpful. From what I can te ...

Unable to apply bootstrap styles to innerHTML using JavaScript

let output = document.getElementById("output") //unable to apply bootstrap styles to <div> and <table> <div class="container"><table class="table"> output.innerHTML = "<div><table><thead><tr& ...

What is the best way to combine relative paths or create distinct identifiers for SVG files located within multiple layers of folders

I have a collection of icons exported from "Figma" organized in folders, and I'm using grunt-svgstore to create a sprite sheet. However, the result contains duplicated IDs even after trying 'allowDuplicateItems: false' and 'setUniqueIds ...

The JSON API fetch request is failing because of Cross-Origin Read Blocking (CORB) restrictions preventing data retrieval

I am struggling with the persistent issue of receiving the (settings.js:76 Cross-Origin Read Blocking (CORB) blocked cross-origin response) error whenever I use the fetch method to retrieve JSON data from an API. Below is the snippet of code that I am cu ...

Retrieving Text Between HTML Tags Using jQuery

Disclosure: I am fully aware of the messy HTML code in this legacy application. Unfortunately, due to its extensive dependencies, making any changes to the HTML structure is not feasible. Despite the circumstances, here is the code snippet at hand: <t ...

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...

When working with NextJs and MikroORM, encountering the error "Cannot use import statement outside a module

Resolving SyntaxError When Integrating MikroORM with NextJS Challenge Encountered While attempting to incorporate MikroORM v6.3.13 into a NextJS v14.2.14 project, I encountered a critical issue. At this point, my primary goal is to establish the setup cor ...

The date of posting will always be '0000-00-00 00:00:00'

I'm experiencing an issue with my JavaScript code for writing reviews. Previously, it worked fine, but now the 'datePosted' column consistently outputs the default '0000-00-00 00:00:00'. writeReview(request, respond) { va ...

Retrieving data from an Array containing a mix of string and integer values represented as strings, organized by the length of the

Imagine you have an array structured like this: employeeArr = ['Steve', '80000', 'Jen', '90000', 'Bob', '40000'] Where employeeArr[0] and employeeArr[2] represent employee names, and employeeA ...

Dealing with special characters in a json XMLHttpRequest: A guide

I'm currently grappling with the best approach for handling special or foreign characters within an AJAX request. My current test code is as follows: var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST","test.json",true); xmlhttp.setRequestHeader ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...

Continuing to reference outdated JSON data even after refreshing the page, instead of utilizing the most recent version

I have a query regarding JSON and JavaScript. I update the JSON file through a web page and save it to the server. However, when I visit the page where the information from the JSON should be displayed, it shows the old data even after refreshing. The upda ...

The initial attempt to use autocomplete with Jquery UI is not functioning as expected upon entry

I'm facing a frustrating issue that's driving me crazy. I'm not an expert in javascript, but I believe the solution is simple. I'm using jQuery UI autocomplete with data retrieved from Ajax. The problem is, I only get the desired resul ...