将package.json依赖项用作gulpfile.js中的文件夹结构

问题描述 投票:0回答:1

我正在尝试创建一个自动化过程,以在项目中包括节点模块。一些模块包含css,因此我试图以一种gulpfile.js的方式来读取这些模块并包含该模块的css。

我试图保持选择性,并且只选择我作为依赖项安装的文件夹。不是整个node_modules文件夹。

我的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')
    );
}

当我运行“ gulp样式”时,该功能运行良好,但是不包括所需的样式。我在做什么错?

gulp node-modules package.json gulp-sass
1个回答
0
投票

首先,有一种更简单的方法来获取package.json文件:

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

然后,您需要依赖项的名称,它们是dependencies对象中的键。将它们映射到一个glob,如下所示:

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

最后,在styles任务中解构该数组:

return src([files.cssPath, ...files.modulesPath])
© www.soinside.com 2019 - 2024. All rights reserved.