2017-09-24 65 views
1

繼續學習javascript幾個星期,我想了解全局範圍變量,以及如何在函數內定義它們以在全局範圍內使用它們。通過DOM選擇器設置函數中的gulp和全局變量

首先,這是我gulfile樣本:

"use strict"; 

var gulp = require('gulp'), 
    rename = require("gulp-rename"), 
    pug = require('gulp-pug'), 
    puglint = require('gulp-pug-lint'), 
    dom = require('gulp-dom'), 
    projectName, // Trying to declare a yet undefined global variable (don't know if its the right way) 
    PATH = { 
    HTML: { 
     NAME: projectName + '.html', // This PATH won't be used before the variable value will be set 
     SRC: 'dev/main.pug', 
     DEST: 'dist/' 
    } 
    }; 

// Compile html from pug and set the html title to a global variable 
gulp.task('html', function() { 
    return gulp.src(PATH.HTML.SRC) 
    .pipe(puglint()) 
    .pipe(pug({ 
     pretty: true 
    })) 
    .pipe(dom(function() { 
     projectName = this.getElementsByTagName("title")[0].innerHTML; // Trying to set the variable's value at a global scope, but doesn't work... 
     return this; 
    })) 
    .pipe(rename(PATH.HTML.NAME)) 
    .pipe(gulp.dest(PATH.HTML.DEST)); 
}); 

所以,我想要做的是讓「標題」我處理文件的innerHTML的,並將其分配給一個全局變量,使它可用於其他功能。 但它返回的是「未定義」。 思考,這是因爲的處理順序問題可能是,我這樣想我的命名管道改成這樣:

... 
.pipe(rename(projectName + '.html')) 
... 

但即使如此,它仍然會返回undefined(這樣的話,輸出一個名爲「undefined.html」) 。

我不知道問題是否來自變量本身,或者可能是我對getElementsByTagName("title")[0].innerHTML的調用未正確設置並返回undefined

任何人都可以幫忙嗎? 在此先感謝。

回答

0

這裏的問題是你在pug文件上運行你的dom函數。 gulp dom函數應該在HTML文件上運行。

在將.pug文件轉換爲HTML文件之前,請先使用管道dom函數。

添加另一個gulp任務,執行pug文件轉換後的dom函數。這樣你就不會得到undefined的值。

一個示例實現應該如下所示。

gulp.task('dom', function() { 
    return gulp.src('./src/index.html') 
     .pipe(dom(function(){ 
      return this.querySelectorAll('body')[0].setAttribute('data-version', '1.0'); 
     })) 
     .pipe(gulp.dest('./public/')); 
}); 

閱讀更多關於dom功能。
https://www.npmjs.com/package/gulp-dom

+0

好的!我認爲通過在'pug'管道之後傳遞'dom'函數,流應該看起來像是「真正的」html標記文件。解決我的問題的另一種方法也是直接從.pug文件中提取標題。我會找出並進行一些搜索。否則,我可能不得不創建一個新任務(就像你建議我這樣做)並添加帕格任務作爲依賴。謝謝您的回答 ! –