0

I'm trying to create an automated process for including node modules in my projects. Some modules have css included, and so I'm trying to make gulpfile.js in a way it can read those modules and include the css of that module.

I try to be selective and have only the folders selected that I install as a dependency. Not the entire node_modules folder.

My gulpfile.js:

// Import (not showing all for the sake of the question)
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const fs = require('fs');
const json = JSON.parse(fs.readFileSync('./package.json'));

// File paths
const files = { 
    cssPath: 'assets/styles/**/*.scss',
    jsPath: 'assets/scripts/**/*.js',
    imgPath: 'assets/images/**/*',
    modulesPath: ['node_modules']+json.dependencies+'/**/*.scss'
    //Desired output: node_modules/module_name/all_folders/all.scss
}

// Compile CSS
function styles(){
    return src([files.cssPath, files.modulesPath])
        .pipe(sourcemaps.init())
        .pipe(sass())
        .pipe(postcss([ autoprefixer(), cssnano() ]))
        .pipe(sourcemaps.write('.'))
        .pipe(dest('dist/styles')
    );
}

When I run "gulp styles" the function runs just fine, but the desired styles are not included. What am I doing wrong?

1 Answer 1

2

First, there's an easier way to get your package.json file:

const package = require('./package.json');

Then you need the names of your dependencies, which are the keys in the dependencies object. Map these to a glob, like this:

const files = {
  ...
  modulesPath: Object.keys(package.dependencies).map(module => `node_modules/${module}/**/*.scss`)
}

Lastly, destructure that array in your styles task:

return src([files.cssPath, ...files.modulesPath])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.