Search code examples
javascripthtmlcssnpmgulp

How to properly include CSS&JS files installed as an NPM package with gulp?


How to properly include to index.html CSS&JS files installed as an NPM package with gulp?

I've installed one of the CSS frameworks (Materialize) with NPM: npm install --save-dev materialize-css

Now I want to include CSS and JS files from this framework to my index.html. They are located under node_modules/materialize-css/dist/css/materialize.min.css and node_modules/materialize-css/dist/js/materialize.min.js.

What is the proper way to achieve it, considering that I have gulp under my hand?

Use the full path to files in node_modules from index.html directly?

Copy them to ./dist by using gulp task using absolute paths to the files in gulpfile.js, and reference them from index.html as ./dist/materialize.min.css and ./dist/materialize.min.js?

Any advice would be much appreciated. Sorry if the question is dumb, it's just hard to find "the right way" to solve this task.


Solution

  • I've ended up with the following solution in gulpfile.js (my example uses materialize-css as an npm package with css/js files that I want 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)));
    }
    

    require.resolve(relative_path) automatically resolves a relative file name in node_modules directory. slash is used to convert double backslash on Windows to a single forward slash.