Gulp.js访问流

时间:2017-06-21 15:22:05

标签: javascript json node.js gulp

我有一系列导出JSON的JS文件。我想从每个文件中获取导出的JSON,因此我可以将其传输到另一个插件。我如何访问流中每个文件的module.exports?是否有插件?

示例JS文件:

let typographyFamilyFallback = 'Verdana, sans-serif';
let typographyFamily = 'Gotham, gotham, ' + typographyFamilyFallback;
let typographyFamilyFineprint = typographyFamily;
let typographyBaseSize = 15;

let typographyJSON = {
    typographyFamilyFallback,
    typographyFamily,
    typographyFamilyFineprint,
    typographyBaseSize
};

module.exports = typographyJSON;

gulpfile.js:

const gulp = require('gulp');
const jsonCss = require('gulp-json-css');

gulp.task('generate-less-vars', function() {
  return gulp
    .src(['./src/variables/*.js'])
    // Get the module.export and convert to json for the next piped task.
    .pipe(jsonCss({targetPre: 'less'}))
    .pipe(gulp.dest('target/static-zsg/zsg/variables/'));
});

1 个答案:

答案 0 :(得分:0)

这是我最终做的事情:

我已经设置了多个.js文件,所以我构造了一个对象,其中的键来自文件名,值是一个require语句。然后对象循环。对于每个项目我JSON.stringify该值,将其发送到gulp文件,管道到jsonCss并写入我的目标目录。

JS档案

let typographyFamilyFallback = 'Verdana, sans-serif';
let typographyFamily = 'Gotham, gotham, ' + typographyFamilyFallback;
let typographyFamilyFineprint = typographyFamily;
let typographyBaseSize = 15;

let typographyJSON = {
    typographyFamilyFallback,
    typographyFamily,
    typographyFamilyFineprint,
    typographyBaseSize
};

module.exports = typographyJSON;

<强> gulpfile.js

const jsVars = {
    layout: require('./src/static-zsg/zsg/variables/_layout'),
    trapezoid: require('./src/static-zsg/zsg/variables/_trapezoid'),
    typography: require('./src/static-zsg/zsg/variables/_typography')
}
gulp.task('generate-less-vars', function() {
    for (let key in jsVars) {
        const variableJson = JSON.stringify(jsVars[key]);
        file(`${key}.json`, `${variableJson}`)
            .pipe(jsonCss({targetPre: 'less'}))
            .pipe(gulp.dest(`target/static-zsg/zsg/variables/`));
    }
});