在前端開發過程當中,咱們須要在開發過程當中,將開發中的站點部署到服務器上,而後,在瀏覽器中查看實際的效果,在 Grunt 環境下,能夠直接使用集成在 Grunt 中的 Connect 插件完成站點服務器的支持,在開發過程當中,直接查看效果。html
與 Grunt 集成的 Connect 能夠在 GitHub 上找到,地址:https://github.com/gruntjs/grunt-contrib-connect前端
安裝的時候,直接經過 NPM 就能夠,不用本身下載。執行下面的命令將 grunt-contrib-connect 安裝到你的項目中。git
npm install grunt-contrib-connect --save-dev
安裝以後,須要在你的 Gruntfile.js 項目文件中,加載這個插件。github
grunt.loadNpmTasks('grunt-contrib-connect');
具體的配置信息見下一步了。web
在你的 Gruntfile.js 中,添加一個 connect 的配置節。chrome
在 connect 中設置一個 connect 任務的名字,注意不要叫 options ,這是 connect 保留的配置名。咱們這裏稱爲 server。npm
完成以後的 Gruntfile.js 文件以下:數組
'use strict';
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ connect: { server: { options: { port: 8000, hostname: '*', base: ['src/'] } } } }); grunt.loadNpmTasks('grunt-contrib-connect'); }
這裏的配置是說服務器將工做在 8000 端口,網站的根目錄映射到物理目錄的 src/ 中。瀏覽器
咱們能夠在 src 中建立一個名爲 index.html 的網頁,進行測試。
保存配置文件以後,在命令行執行 grunt connect服務器
PS C:\study\grunt> grunt connect
Running "connect:server" (connect) task Started connect web server on http://localhost:8000 Done, without errors.
在執行 Grunt 的過程當中,網站服務器將會啓動,你能夠經過瀏覽器來訪問這個服務器。可是,在 grunt 執行完成以後,服務器將會被自動關閉。因此,你可能根原本不及切換到瀏覽器去訪問你的頁面。
使用 keepalive 這個選項可使得 grunt 在執行到 connect 的時候,不會退出這個任務,保持服務器的持續執行,這樣你就能夠一直訪問這個服務器了。可是,須要注意的是,這個 grunt 任務會阻塞後繼任務的執行,因此,你須要將這個任務排在最後一個任務。
'use strict';
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ connect: { server: { options: {
protocol: 'http', port: 8000, hostname: '*', keepalive: true, base: ['src/'] } } } }); grunt.loadNpmTasks('grunt-contrib-connect'); }
這個時候,從新執行 grunt connect 就會看到 Waiting forever... 的輸出,直到你 Ctrl+C 終止這個任務,grunt 會一直停留在 connect 這個任務上。
PS C:\study\grunt> grunt connect
Running "connect:server" (connect) task Waiting forever... Started connect web server on http://localhost:8000 ^CTerminate batch job (Y/N)? y
在這一步,咱們配置了以下的服務器參數:
若是你但願在啓動服務以後,自動打開瀏覽器,而不用本身打開瀏覽器,再輸入訪問地址,能夠將 open 設置爲 true。
open 能夠設置 boolean, 字符串,對象。
默認爲 false,設置爲 true 將會自動打開瀏覽器。
若是設置爲字符串,則爲瀏覽器打開的地址。
對象的配置將會直接傳遞給 open 處理。
{
target: 'http://localhost:8000', // target url to open, 目標路徑 appName: 'chrome', // name of the app that opens, ie: open, start, xdg-open,自動啓動的應用名稱, 好比你的瀏覽器:chrome callback: function() {} // called when the app has opened }
能夠配置爲 boolean 或者 數值,用來表示是否支持 livereload。
設置爲 true 或者數值表示支持 connect-livereload,可是這個設置不能直接使用,須要 connect-livereload 的配合,因此並不能直接實現自動加載。你還須要 grunt-contrib-watch 或者其餘的庫支持來實現文件修改時的自動加載。
下一次咱們將會介紹這個 livereload 的使用。
如何使用端口,若是設置爲 true,則任務會尋找 port 指定的下一個可用的端口,默認爲 false.
服務建立以後的回調函數,容許集成其它庫到網站中,例如,集成 Socket.IO 的示例。注意,這須要你先準備好了 socket.io 模塊。
grunt.initConfig({
connect: {
server: {
options: {
port: 8000, hostname: '*', onCreateServer: function(server, connect, options) { var io = require('socket.io').listen(server); io.sockets.on('connection', function(socket) { // do something with socket }); } } } } });
很顯然,網站處理的中間件。若是你以爲這個默認的靜態文件服務器不夠強大的話,能夠經過中間件進行擴展。
能夠配置一個函數或者數組,默認爲使用 options.base 處理靜態文件和目錄瀏覽的數組。
若是提供了一個數組的話,就會取代默認的服務器處理,直接採用自定義的中間件進行處理,這須要咱們徹底定義服務器中的處理。
數組的示例
grunt.initConfig({
connect: {
server: {
options: {
middleware: [
function myMiddleware(req, res, next) { res.end('Hello, world!'); } ], }, }, }, });
若是是函數的話,會自動添加默認的靜態文件處理中間件,再執行自定義的中間件函數。
函數的示例
grunt.initConfig({
connect: {
server: {
options: {
middleware: function(connect, options, middlewares) { // inject a custom middleware into the array of default middlewares middlewares.unshift(function(req, res, next) { if (req.url !== '/hello/world') return next(); res.end('Hello, world from port #' + options.port + '!'); }); return middlewares; }, }, }, }, });
這部分的源碼以下:
// The middleware options may be null, an array of middleware objects, // or a factory function that creates an array of middleware objects. // * For a null value, use the default array of middleware // * For a function, include the default array of middleware as the last arg // which enables the function to patch the default middleware without needing to know // the implementation of the default middleware factory function var middleware; if (options.middleware instanceof Array) { middleware = options.middleware; } else { middleware = createDefaultMiddleware.call(this, connect, options); if (typeof(options.middleware) === 'function') { middleware = options.middleware.call(this, connect, options, middleware); } }
能夠配置多個服務器,須要注意的是,若是有一個服務器的 keepalive 設置爲 true,就會阻塞其它的服務器。
// Project configuration. grunt.initConfig({ connect: { site1: { options: { port: 9000, base: 'www-roots/site1' } }, site2: { options: { port: 9001, base: 'www-roots/site2' } } } });
使用 https 協議須要預先進行證書的配置。
若是沒有證書的話,可使用 OpenSSL 建立自簽名的證書做爲本地的根證書。
### Create ca.key, use a password phrase when asked
### When asked 'Common Name (e.g. server FQDN or YOUR name) []:' use your hostname, i.e 'mysite.dev' openssl genrsa -des3 -out ca.key 1024 openssl req -new -key ca.key -out ca.csr openssl x509 -req -days 365 -in ca.csr -out ca.crt -signkey ca.key ### Create server certificate openssl genrsa -des3 -out server.key 1024 openssl req -new -key server.key -out server.csr ### Remove password from the certificate cp server.key server.key.org openssl rsa -in server.key.org -out server.key ### Generate self-siged certificate openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
而 Gruntfile.js 中則須要進行相應的配置。
// Project configuration. grunt.initConfig({ connect: { server: { options: { protocol: 'https', port: 8443, key: grunt.file.read('server.key').toString(), cert: grunt.file.read('server.crt').toString(), ca: grunt.file.read('ca.crt').toString() }, }, }, });
若是你已經看到這裏,你應該可使用 grunt 建立一個開發中的測試服務器。