我正在尝试创建一个自动化过程,以在项目中包括节点模块。一些模块包含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样式”时,该功能运行良好,但是不包括所需的样式。我在做什么错?
首先,有一种更简单的方法来获取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])