Gulp - 如何发现相对路径深度?

时间:2018-05-25 09:41:11

标签: node.js npm gulp

我在一个存储库中有一个项目,它应该在根文件夹中有核心文件,在整个项目中使用,以及具有各自独特设置和构建过程的单独主题文件夹。

项目如下:

core/
themes/
   some/long/folder/for/a/theme/root/
       theme-folders/
       gulpfile.js
   another/theme/folder/root/
       theme-folders/
       gulpfile.js
config.json

每个主题文件夹都有自己的gulpfile.js。当我想启动gulp进程时,我从所需的主题文件夹启动它。

我使用的Gulp和gulp插件只能用相对路径工作,使用绝对路径是不可能的。手动发现相对路径的目录深度是有问题的,我希望自动化这个过程。

问题是 - 如何从一个gulpfile.js到项目根目录发现目录深度,其中config.json位于哪里?

2 个答案:

答案 0 :(得分:1)

也许这会有所帮助。使用此文件夹结构:

pathRelative  (the repository level)

├───core 
└───themes
    ├───a
│       └───b
│           └───c
│               └───d
│                   └───root
│                       └───theme-folders
    └───h
        └───i
            └───j
                └───root
                    └───theme-folders

const gulp = require('gulp');
const path = require('path');

// set the repository path
// I couldn't figure out a way to retrieve this programmatically

let cwdRoot = "C:\\Users\\Mark\\OneDrive\\Test Bed\\pathRelative"

gulp.task('default', function () {

  // get full path to current working root folder
  // fullPath = C:\Users\Mark\OneDrive\Test Bed\pathRelative\themes\a\b\c\d\root

  let fullPath = path.resolve();
  console.log("fullPath = " + fullPath);

  // get folders from the cwdRoot to the current working folder
  //  folders = pathRelative\themes\a\b\c\d\root

  let folders = path.relative( cwdRoot, fullPath );
  console.log("folders = " + folders);

  let folderDepth = folders.split(path.sep).length;
  console.log(folderDepth);

  // 6 for the themes/a/b/c/d/root
  // 5 for the themes/h/i/j/root
});

答案 1 :(得分:0)

根据马克的答案,我已经制定了自己的解决方案。有一个插件可以确定应用程序的根文件夹,它被称为app-root-path



const gulp = require('gulp');
const path = require('path');
const appRoot = require('app-root-path');

gulp.task('default', function () {

	// Function to calculate directory depth
	const dirDepth = (myDir) => {
		return myDir.split(path.sep).length;
	};

	console.log('Current directory = ' + __dirname);
	console.log('Root direcotry = ' + appRoot.path);
	console.log('Depth difference = ' + (dirDepth(__dirname) - dirDepth(appRoot.path)));

	var rel = '..' + path.sep;
	var depth = dirDepth(__dirname) - dirDepth(appRoot.path);
	var relPath = rel.repeat(depth);

	console.log('Relative path from current folder to root is: ' + relPath);

	var pkg = require(relPath + 'package.json');

	console.log('Test to see if it works: ' + pkg.name);
});