Run gulp from child directories?

假如想象 提交于 2019-12-11 00:36:59

问题


I currently have a file structure like this

SASS
    gulpfile.js
    node_modules
    sites
        example-site
            scss
            css
        example-site-two
            scss
            css
        example-site-three
            scss
            css

I have gulp installed in the main parent SASS folder with a task 'sass-all' that can go through every single sites scss folder and compile it into css.

I'm trying to write a new task called 'sass-single' which can be run from any of the example-site folders. So let's say I'm in the folder "example-site-two", I want to be able to cmd and do 'gulp sass-single' and ONLY have it compile the SASS in this site. Same thing for a watch-single task I'd like to setup.

Problem is whenever I run this task from a site folder, it changes my working directory up to the parent SASS folder. I don't want to have 100 different tasks for every different site, I'd prefer to just have one 'sass-single' task thats smart enough to only compile the files from the folder I was in when I ran the script.

current Gulp task attempt

    gulp.task('sass-single', function () {
      process.chdir('./');

      // Where are the SCSS files?
      var input = './scss/*.scss';

      // Where do you want to save the compiles CSS file?
      var output = './css';

      return gulp
        .src(input)
        .pipe(sourcemaps.init())
        .pipe(sass(sassOptions).on('error', sass.logError))
        .pipe(postcss(processors))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(output));
    });

However this goes back to the main SASS folder and then just does nothing. How would I go about modifying this to be able to run from any site folder and have it only do it for that site?


回答1:


If you want to change the current working directory (CWD) back to the directory where you invoked gulp then this won't work:

process.chdir('./');

That's a relative path. Relative paths are relative to the CWD. But by the time you execute process.chdir('./') Gulp has already changed the CWD to the directory where your Gulpfile.js is located. So you're just changing the CWD to ... the CWD.

You could explicitly pass a CWD to gulp on the command line:

SASS/sites/example-site> gulp --cwd .

But that would get annoying pretty quickly.

Luckily for you Gulp stores the original CWD in process.env.INIT_CWD before changing it. So you can use the following in your task to change the CWD back to the original:

process.chdir(process.env.INIT_CWD);


来源:https://stackoverflow.com/questions/36891227/run-gulp-from-child-directories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!