創建 Web 前端開發環境


 Web 前端開發涉及多種工具,這里將常用工具的安裝和配置進行說明,提供了詳細的說明,為后繼的開發創建一個堅實的基礎。

本文介紹的工具有:NodeJS, NPM, Bower, Git 和 Grunt。

1. 安裝 NodeJS 和 NPM

一切從 NodeJS 開始吧,官方網址:https://nodejs.org/

NodeJS 既可以為我們提供一個服務器端的 Web 環境,又可以提供一個命令行的工具,既然做 Web 前端開發,那就是我們必然選擇的工具了。

為了解決包管理的問題,NodeJS 自己搞了一個包管理工具,你可以看成是 Visual Studio 中的 Nugut 就好了。不過,這個工具太好用了,現在自己已經自立門戶,所以,你也可以單獨安裝它。 

 

NPM 官方網址:https://www.npmjs.com

有的時候,在國內訪問 NPM 不太方便,原因你懂得,淘寶在國內架設了一個 CNPM 服務器,幫我們同步 NPM 中的模塊,這個 CNPM 的地址為:http://npm.taobao.org,淘寶大法好。

具體如何配置 Node.js 和 NPM,我已經整理過一篇 配置 node.js 環境,可以用來參考。

地址:http://www.cnblogs.com/haogj/p/3969536.html 

使用 npm 的 init 命令可以直接交互式創建一個 NodeJS 的項目文件 package.json.

PS C:\Study\framework> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (framework)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:\Study\framework\package.json:

{
  "name": "framework",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "grunt": "^0.4.5",
    "grunt-contrib-jshint": "^0.11.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)

 這時候,當前目錄下,會出現一個名為 package.json 的 NodeJS ,或者說是 NPM 的項目模板。

如果你喜歡簡單快捷的話,不喜歡一步一步地回答這些問題,還可以加上一個參數 -y,將所有文件的答案默認為回答 yes。

npm init [-f|--force|-y|--yes]

 

 詳細的 init 命令的使用可以參考這里

2. 安裝 Bower

注:現在不推薦 Bower了,你可以跳過這一段。

NPM 可以管理 node.js 的模塊,可以,我們准備做 Web 前端開發,現在的目標不是 node.js 的服務器端開發,所以,我們更加需要在瀏覽器上使用的 javascript 模塊,這就不能全靠 NPM 了,Bower 是一個 Web 前端模塊的包管理工具,有了它,我們就不必到各個網站去找各種前端模塊,比如 jquery,bootstrap 等等,直接使用這個工具就可以搞定了。按照官方說法:Bower manages all these things for you. 

Bower 的圖標是一只小鳥,很漂亮。查了一下,它叫園丁鳥,鳥類的建築大師,雄鳥在求偶期會用樹枝築拱門或亭子,鳥中的工匠呀。

官網地址:http://bower.io,你也可以在 GitHub 上找到它:https://github.com/bower/bower

安裝 bower 需要使用 NPM,命令很簡單。

$ npm install -g bower

安裝之后,可以直接使用 bower 命令來管理。下面是使用說明。

PS C:\Study\framework> bower

Usage:

    bower <command> [<args>] [<options>]
Commands:

    cache                   Manage bower cache
    help                    Display help information about Bower
    home                    Opens a package homepage into your favorite browser
    info                    Info of a particular package
    init                    Interactively create a bower.json file
    install                 Install a package locally
    link                    Symlink a package folder
    list                    List local packages - and possible updates
    login                   Authenticate with GitHub and store credentials
    lookup                  Look up a package URL by name
    prune                   Removes local extraneous packages
    register                Register a package
    search                  Search for a package by name
    update                  Update a local package
    uninstall               Remove a local package
    unregister              Remove a package from the registry
    version                 Bump a package version
Options:

    -f, --force             Makes various commands more forceful
    -j, --json              Output consumable JSON
    -l, --log-level         What level of logs to report
    -o, --offline           Do not hit the network
    -q, --quiet             Only output important information
    -s, --silent            Do not output anything, besides errors
    -V, --verbose           Makes output more verbose
    --allow-root            Allows running commands as root
    -v, --version           Output Bower version
    --no-color              Disable colors
See 'bower help <command>' for more information on a specific command.
PS C:\Study\framework>

bower 會將管理的包保存到 bower_components/ 目錄下面。

使用 init 進行初始化。

PS C:\Study\framework> bower init
? name: framework
? version: 0.0.0
? description:
? main file:
? what types of modules does this package expose? amd
? keywords:
? authors:
? license: MIT
? homepage:
? set currently installed components as dependencies? Yes
? add commonly ignored files to ignore list? Yes
? would you like to mark this package as private which prevents it from being accidentally published to the registry? (y
? would you like to mark this package as private which prevents it from being accidentally published to the registry? Yes
{
  name: 'framework',
  version: '0.0.0',
  moduleType: [
    'amd'
  ],
  license: 'MIT',
  ignore: [
    '**/.*',
    'node_modules',
    'bower_components',
    'test',
    'tests'
  ]
}

? Looks good? Yes

可以看到幫助創建的 bower.json 配置文件的內容。

使用 bower 獲取前端庫很方便,命令類似與 NPM

PS C:\Study\framework> bower install jquery
bower jquery#*                  cached git://github.com/jquery/jquery.git#2.1.4
bower jquery#*                validate 2.1.4 against git://github.com/jquery/jquery.git#*
bower jquery#~2.1.4            install jquery#2.1.4

jquery#2.1.4 bower_components\jquery
PS C:\Study\framework> bower install angularjs
bower angularjs#*               cached git://github.com/angular/bower-angular.git#1.4.5
bower angularjs#*             validate 1.4.5 against git://github.com/angular/bower-angular.git#*
bower angular#~1.4.5           install angular#1.4.5

angular#1.4.5 bower_components\angular
PS C:\Study\framework> bower install bootstrap
bower bootstrap#*               cached git://github.com/twbs/bootstrap.git#3.3.5
bower bootstrap#*             validate 3.3.5 against git://github.com/twbs/bootstrap.git#*
bower bootstrap#~3.3.5         install bootstrap#3.3.5

bootstrap#3.3.5 bower_components\bootstrap
└── jquery#2.1.4

當前目錄下會增加一個 bower_components 文件夾,包含獲取的前端包。不過你不能獲取 kendoUI 的庫,這是一個商業項目。

bower 工作的時候需要 node, npm 和 git.

還沒有 git ?先等一下,我們再來一個工具 git。

3. 安裝 git

如果你不知道 git ,總該聽說過 GitHub 吧,就是這只小黑貓  。不過,我們這里說的是 git ,而不是 GitHub。

Git是一個分布式的版本控制系統,最初由 Linus Torvalds 編寫,Torvalds 着手開發 Git 是為了作為一種過渡方案來替代 BitKeeper,后者之前一直是 Linux 內核開發人員在全球使用的主要源代碼工具。開放源碼社區中的有些人覺得 BitKeeper 的許可證並不適合開放源碼社區的工作,因此 Torvalds 決定着手研究許可證更為靈活的版本控制系統。

后來 Git 在其它項目中也取得了很大成功。GitHub 是使用 git 技術的一個代碼托管網站,提供基於 Web 的訪問界面。是目前最為流行的源代碼管理網站。

Git 官網地址:http://www.git-scm.com

Git 下載地址:http://www.git-scm.com/downloads

安裝非常簡單,Windows 版本下載之后,會得到一個安裝程序,直接安裝就可以。

在命令行直接執行 git 可以得到幫助說明。

PS C:\Study\framework> git
usage: git [--version] [--help] [-C <path>] [-c name=value]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone      Clone a repository into a new directory
   init       Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
   add        Add file contents to the index
   mv         Move or rename a file, a directory, or a symlink
   reset      Reset current HEAD to the specified state
   rm         Remove files from the working tree and from the index

examine the history and state (see also: git help revisions)
   bisect     Find by binary search the change that introduced a bug
   grep       Print lines matching a pattern
   log        Show commit logs
   show       Show various types of objects
   status     Show the working tree status

grow, mark and tweak your common history
   branch     List, create, or delete branches
   checkout   Switch branches or restore working tree files
   commit     Record changes to the repository
   diff       Show changes between commits, commit and working tree, etc
   merge      Join two or more development histories together
   rebase     Forward-port local commits to the updated upstream head
   tag        Create, list, delete or verify a tag object signed with GPG

collaborate (see also: git help workflows)
   fetch      Download objects and refs from another repository
   pull       Fetch from and integrate with another repository or a local branch
   push       Update remote refs along with associated objects

'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command>' or 'git help <concept>'
to read about a specific subcommand or concept.

在前端開發過程中,我們不用直接使用 git,有的時候 bower 會自動調用 git 來獲取代碼。 

 

4. 安裝 Grunt

如果你選擇 Webpack 的話,可以跳過這一段。這里是 Webpack 的安裝說明

對於需要反復重復的任務,例如壓縮(minification)、編譯、單元測試、linting等,自動化 Grunt 工具可以減輕你的勞動,簡化你的工作。

官網地址:http://gruntjs.com

中文地址:http://www.gruntjs.net

Grunt和 Grunt 插件是通過 npm 安裝並管理的。

詳細的說明可以從 這里開始

在安裝 Grunt 前,請確保當前環境中所安裝的 npm 已經是最新版本,執行 npm update -g npm 指令進行升級(在某些系統中可能需要 sudo 指令)。

如果你已經安裝了 Grunt,現在需要參考一些文檔手冊,那就請看一看 Gruntfile 實例 和如何 配置任務吧。

安裝 CLI

在繼續學習前,你需要先將Grunt命令行(CLI)安裝到全局環境中。安裝時可能需要使用sudo(針對OSX、*nix、BSD等系統中)權限或者作為管理員(對於Windows環境)來執行以下命令。

npm install -g grunt-cli

上述命令執行完后,grunt 命令就被加入到你的系統路徑中了,以后就可以在任何目錄下執行此命令了。

顯示 Grunt 版本,注意是大寫的 V,小寫的 v 就是另外一個意思了。

>grunt -V
grunt-cli v0.1.13
grunt v0.4.5

Grunt 使用的項目文件稱為 Gruntfile.js。如果還沒有 Gruntfile.js 文件,直接執行 grunt,會看到如下的提示信息。

PS C:\Study\framework> grunt
grunt-cli: The grunt command line interface. (v0.1.13)

Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or grunt
hasn't been installed locally to your project. For more information about
installing and configuring grunt, please see the Getting Started guide:

http://gruntjs.com/getting-started

這是說沒有在當前目錄下找到 grunt 的項目文件。

grunt 的項目文件稱為 Gruntfile.js,注意第一個字符可是大寫的,在跨平台的時候,這就是一個坑了。

讓我們寫一個 Grunt 版的 Hello, world 來完成環境的准備。

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),
  });

  grunt.registerTask('default', 'Hello, world task description.', function() {
      grunt.log.writeln('Hello, world.');
  });

};

這里,我們創建了一個自定義的任務,設置名稱為 default,實際執行的時候,會輸出 Hello, world.

PS C:\Study\framework> grunt
Running "default" task
Hello, world.

Done, without errors.

 

5. 安裝 Webpack

這里是 Webpack 的安裝說明

 就到這里吧。下次再見。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM