一、初始化項目
1. vue-cli
vue-cli 是 vue.js 的腳手架工具,可以幫助我們編寫基礎代碼、快速搭建開發環境。
使用 vue-cli 工具之前,首先安裝 node 和 npm 包管理工具。
2. 初始化項目步驟
2.1 全局安裝 vue-cli 工具
npm install -g vue-cli
2.2 使用命令搭建項目
vue init <模板名稱> <項目名稱>
2.3 下載依賴
npm install
2.4 運行開發測試服務器,瀏覽器自動打開地址 http://localhost:8080/
npm run dev
2.5 注意:
從淘寶鏡像下載,可提高安裝速度,運行如下命令:
npm config set registry https://registry.npm.taobao.org/
想要恢復原樣,只需運行如下命令:
npm config delete registry
2.6 例子:基于 webpack 模板,創建 first-test-vue 項目
$ npm install -g vue-cli // 全局安裝 vue-cli
$ vue init webpack first-test-vue // 初始化命令
? Project name first-test-vue // 項目名稱
? Project description A Vue.js project // 項目描述
? Author NathanYang // 作者
? Vue build standalone // 獨立構建
? Install vue-router? Yes // 安裝路由
? Use ESLint to lint your code? Yes // 安裝 ESLint 代碼檢測工具
? Pick an ESLint preset Standard
? Setup unit tests with Karma + Mocha? Yes
? Setup e2e tests with Nightwatch? No // 端到端測試
vue-cli · Generated "first-test-vue".
To get started:
cd first-test-vue // cd 進入 first-test-vue 項目
npm install // 安裝依賴
npm run dev // 開始運行:webpack 持續運行
Documentation can be found at https://vuejs-templates.github.io/webpack
二、目錄結構
first-test-vue
├── build # 存放構建腳本,例如 webpack 配置文件
├── config # 存放配置信息
├── node_modules # 依賴
├── src # 除首頁外,其他源代碼
├── assets # 存放代碼之外的資源,例如圖片、字體等
├── components # 存放主組件之外的組件,vue 組件的后綴都是 .vue
├── router # 路由
├── App.vue # 主組件
└── main.js # JS 入口文件
├── static # 存放靜態資源
└── test # 單元測試代碼
├── .babelrc # babel 配置文件
├── .editorconfig
├── .eslintignore
├── .eslintrc # ESLint 配置文件
├── .gitignore
├── .postcssrc
├── index.html # 首頁
├── package.json
└── README.md
三、生成預覽鏈接
3.1 首先,找到 config/index.js 中的 assetsPublicPath
并將其改為: assetsPublicPath: '/<github 項目名稱>/dist'
例如本項目: assetsPublicPath: '/first-test-vue/dist'
3.2 其次,運行命令 npm run build
運行命令 npm run build
后,項目中會自動生成一個 dist
目錄
dist
目錄下的 index.html
需 http 協議
才可預覽到頁面內容,否則空白一片
3.3 最后,使用 git pages 預覽
打開 .gitignore 文件,刪除 dist/
該行,因為需要提交該目錄到 github,然后 push 代碼
在 github 上開啟該項目的 git pages 預覽功能
項目 first-test-vue
實際預覽鏈接:https://NathanYangcn.github.io/first-test-vue/dist/