【问题标题】:Gulp.js access module.exports for each JS file in streamGulp.js 为流中的每个 JS 文件访问 module.exports
【发布时间】:2017-06-21 15:22:04
【问题描述】:

我有一系列导出 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/'));
});

【问题讨论】:

    标签: javascript json node.js gulp


    【解决方案1】:

    这是我最终做的:

    我已经设置了 .js 文件的数量,所以我构造了一个对象,其键来自文件名,值是 require 语句。然后对象被循环。对于我对每个项目的 JSON.stringify 值,将其发送到 gulp-file,将其通过管道传输到 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/`));
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      相关资源
      最近更新 更多