【问题标题】:Using package.json dependencies as folderstructure in gulpfile.js使用 package.json 依赖项作为 gulpfile.js 中的文件夹结构
【发布时间】:2020-02-25 20:55:58
【问题描述】:

我正在尝试创建一个自动化流程,以便在我的项目中包含节点模块。一些模块包含 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 styles”时,函数运行得很好,但不包括所需的样式。我做错了什么?

【问题讨论】:

    标签: gulp node-modules package.json gulp-sass


    【解决方案1】:

    首先,有一种更简单的方法可以获取您的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])
    

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 1970-01-01
      • 2016-04-05
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 2017-04-18
      • 1970-01-01
      相关资源
      最近更新 更多