Guide on effectively incorporating CSS and JS files packaged as an NPM module using gulp

How can I efficiently incorporate CSS and JS files from an NPM package, installed via gulp, into my index.html file?

I have used NPM to install the Materialize CSS framework by running:

npm install --save-dev materialize-css

Now, I need to include the CSS and JS files from this framework in my index.html. These files are located at

node_modules/materialize-css/dist/css/materialize.min.css
and
node_modules/materialize-css/dist/js/materialize.min.js
.

What is the best approach for achieving this task, considering that I am using gulp?

Should I reference the full path to the files in node_modules directly from index.html?

Or should I copy them to ./dist using a gulp task with absolute paths specified in

gulpfile.js</code, and then link them in <code>index.html
as ./dist/materialize.min.css and ./dist/materialize.min.js?

I would greatly appreciate any guidance on this matter. Apologies if this question seems basic, as it's difficult to determine the most effective solution.

Answer №1

After some trial and error, I came up with the solution below in my gulpfile.js. In this example, I am using the npm package materialize-css which includes both css and js files that I need to include:

const slash = require('slash');
const merge = require('merge-stream');

const globs = {
    ...,
    dest: {
        dirs: {
            css: 'dist/css',
            js: 'dist/js'
        }
    },
    materializecss: {
        css: 'materialize-css/dist/css/materialize.min.css',
            js: 'materialize-css/dist/js/materialize.min.js',
            nouislider: {
                css: 'materialize-css/extras/noUiSlider/nouislider.css',
                js: 'materialize-css/extras/noUiSlider/nouislider.min.js'
            }
        }
    };

function vendors() {
    const resolve = (p) => slash(require.resolve(p));
    // prettier-ignore
    return merge(
        src(resolve(globs.materializecss.css))
            .pipe(dest(globs.dest.dirs.css)),
        src(resolve(globs.materializecss.js))
            .pipe(dest(globs.dest.dirs.js)),
        src(resolve(globs.materializecss.nouislider.css))
            .pipe(dest(globs.dest.dirs.css)),
        src(resolve(globs.materializecss.nouislider.js))
            .pipe(dest(globs.dest.dirs.js)));
}

The function require.resolve(relative_path) is used to automatically resolve a relative file name within the node_modules directory. The slash function is crucial for converting double backslashes on Windows into single forward slashes.

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 there is only one space after every 4 characters in a string?

Looking for a way to make social security number input more readable by inserting a whitespace after the first 4 characters in the string. The social security number has a total of 10 numbers, so the desired format is: 1234 567890. Most solutions I found ...

Enhance the Material UI Data Grid by customizing the toolbar's default slots with the option to disable the

https://i.stack.imgur.com/0YV9m.png Background In my current project, I am utilizing the Datagrid component from MUI [email protected]. I have disabled the column menu to display the toolbar at the top of the table instead of on individual columns. ...

What steps can I take to create a slideshow with dynamic animations?

I am trying to create a unique category display by turning it into a slider. When the user clicks on any category, I want it to move to the left and become larger. To see an example of how the sliding effect works, check out this link: slideshow https://i ...

Choose an item from a list that does not have a particular class

Here is a list of items: <ul id='myList'> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li class='item-selected'>Item 4</li> <li>Item 5</li> & ...

Encountering unforeseen permission issues while executing development script on a project built with Vite

Whenever I attempt to run a project using Vite and run the dev script, I encounter this issue. The only way I have been able to resolve it is by running VsCode as an administrator. Changing the folder permissions to Read & Write for all users does not re ...

enclosing a fixed or absolute div within a relative div

I am trying to ensure that the text on my website remains below an absolute positioned menu. The menu is overlaying a div with text, and I want the layout to appear as if the menu was relatively positioned. HTML <nav id="s-nav-wrap"> <di ...

Unusual alterations to HTML and CSS to meet specific needs

Struggling with bringing my website ideas to life! My header contains a navigation bar, followed by a centered chat box within a fixed <section>. Want the left and right side of the chat box to be content areas that scroll in sync while the chat box ...

When using Node.js and geth together, running JavaScript code may lead to the creation of zombie processes, causing the

Currently, I am utilizing a JavaScript code that connects to the web3 package on Ethereum's JSON RPC API. This code is designed to iterate through each transaction in an incoming block. If the transaction involves an internal wallet, it sends the rele ...

Unable to post form data into database due to Javascript undefined data situation

I've been working on an HTML form that can interact with a PHP API to retrieve client data and then update user stats in a MySQL database. Currently, I am converting the data into a JSON object and using JSON.stringify to create a string for sending ...

Dealing with numerous identical ajax requests in jQuery

With 5 text fields where various amounts are entered, I utilize AJAX calls for calculations based on these values. The issue arises when the same AJAX call is repeated each time a user types in order to determine the total amount. The problem lies in the ...

A guide to correctly importing a Json File into Three.js

I've been working on some cool projects in Blender and wanted to showcase one using threejs. However, I'm facing an issue where the object isn't displaying properly. Can someone guide me on how to correctly load a JSON file with keyframe ani ...

Make sure that the webpage does not display any content until the stylesheet has been fully loaded by

I am seeking to utilize ng-href for loading different Themes. One issue I am encountering is that the unstyled content appears before the stylesheet is applied. I have created a Plunker where I made changes to Line 8 in the last 3 Versions for comparison ...

The Intersection Observer encountered an issue as it was unable to access the property 'current' since it was undefined

My current project involves the implementation of IntersectionObserver, but I am facing an issue where I receive the error message Cannot read property 'current' of undefined. Can anyone help me identify what might be causing this problem? useOn ...

How can I conceal the contents of a webpage until the entire page has finished loading before revealing them?

Is there a way to delay displaying my login template until all elements are fully loaded? Currently, when I visit the site, the template appears first followed by fonts and other components. I want to ensure that nothing is shown to the user until the enti ...

Decrease the construction duration within a sprawling Angular 8 project

It takes nearly 10-15 minutes to compile the project in production mode, resulting in a dist folder size of 32MB Here are the production options I am currently using:- "production": { "optimization": true, "outputHashing": "all", ...

Unleash the Power of Animating Your Active Tabs

Is there a way to create animated tabs that slide in when clicked? I've experimented with using transition code but haven't quite achieved the desired effect yet. This is what I currently have: [data-tab-info] { display: non ...

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

A guide to verifying a user's age using JavaScript by collecting information from 3 separate input fields

On page load, only the year input is required for users to fill in. The user can enter their birth year first without providing the month and day. Currently, I have a function that checks if a person is over 16 years old by comparing their birth year with ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

The $_REQUEST variable is functioning properly, while the $_POST variable seems to

I currently have an HTML form using the post method. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type='text/javascript& ...