顯示具有 Github 標籤的文章。 顯示所有文章
顯示具有 Github 標籤的文章。 顯示所有文章

2023年3月11日 星期六

原始碼解析 create-vue 快速建立 Vue 專案


Vue 可以透過下面的指令,接著詢問一系列的問題,按照設定快速初始一個專案。(目前版本為 3.6.1)

npm init vue@latest

實際是執行這個 create-vue,想透過原始碼的解析,來了解怎麼樣做一個類似的功能,這個專案架構是如何、如何達成建立專案的功能。


1. playground

運用 git submodules的功能,主要是將各種條件下的樣板做snapshot,形成另一個 create-vue-templates 專案。


2. scripts

顧名思義分別對應到 package.json 的 scripts 所執行的檔案名。

  • build
  • prepublish
  • snapshot
  • test

3. template

將程式碼依照性質分成不同的目錄,根據使用者的設定將對應的檔案複製或合成等,形成 Vue 的專案。

  • base: 基本必備的程式碼,主要套件為 vue, vite
  • code: HelloWorld.vue 元件以及 vue-router 範例程式碼,會分成有無使用 ts 版本。
  • config: 裡面每個目錄依照套件名稱命名,目錄包含:cypress-ct, cypress, jsx, pinia, playwright, router, typescript, vitest,目錄裡是安裝套件的設定檔。主要會有 package.json 設定安裝那些套件,後續會將內容與現有設定合併,再來以 cypress 為例,會有 cypress.config.jscypress.config.ts,屆時會根據是否有用 ts 來複製對應的檔案。
  • entry: 指的是 vite 打包的 entry main.js,執行 createApp 的功能,總共有預設, pinia, router, pinia+router 這四種版本。
  • eslint
  • tsconfig

4. utils

目錄及檔案合併等方法都在這個目錄裡,檔名命名已經相當清楚。


5. index

主要邏輯在這個檔案

  • 讀 argv 指令
  • 使用 prompts 詢問一連串問題
  • 依照專案名稱等,產生 package.json
  • 複製 base
  • 複製 config
  • 複製 tsconfig
  • 產生 eslint
  • 複製 entry
  • 清除 js or ts 多餘的檔案或重新命名
  • 產生 README.md
  • 專案已完成,顯示指令提示

拆解過後,我覺得最重要的是如何整理出 template/,讓不同的安裝需求可以拆解出來,有秩序地組成這個初始的專案。


2022年7月24日 星期日

mocha + webpack 的 Vue3 元件單元測試

先說結論,我認為不適合用 mocha 進行 vue3 單元測試(@vue/test-utils),反覆查了很久的資料,相關的套件支援度不足等有重重的障礙,根據 @vue/test-utils 目前提供的測試範例,選擇 Vitest 會更適合。

完整程式碼上傳至 Github (連結)。

一、安裝

首先,第一個問題就是 vue 的版本不能太新,目前只支援 3.0.7,因此對應安裝了相同版本的 @vue/server-renderer

npm install --save-dev @vue/server-renderer@3.0.7

再來請安裝 webpck 和 mocha,mochapack,mochapack 是用來讀取 webpack 設定將元件 render 出來的套件,可支援 webpack5 和 mocha 9

npm install --save-dev webpack mocha mochapack

其他有兩個類似的套件:

mochapack 是由 mocha-webpack 延伸而來的,三者用法都非常接近,但上述兩個對 webpack 和 mocha 版本的支援度都比 mochapack 差


再來請安裝 vue3 官方的元件測試套件 @vue/test-utils

npm install --save-dev @vue/test-utils

mocha 不像是 jest 已經內建支援 jsdom、assertion ,所以要另外安裝

npm install --save-dev webpack-node-externals jsdom-global
npm install --save-dev expect


二、設定

新增測試專用的 webpack 設定檔 webpack.config-test.js

// webpack.config-test.js

const nodeExternals = require('webpack-node-externals');
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
    mode: 'development',
    target: 'node',  // webpack should compile node compatible code
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
    devtool: 'inline-cheap-module-source-map',
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    plugins: [
        new VueLoaderPlugin(),
    ],
};

設定 jsdom 設定檔 src/tests/setup.js

// src/tests/setup.js

require('jsdom-global')();

最後,請到 package.json 設定 script 指令

Usage: mochapack [options] [<file|directory|glob> ...]

Options
 --webpack-config  path to webpack-config file
 --require, -r     require the given module
{
  "scripts": {
    "test": "npx mochapack --webpack-config webpack.config-test.js --require src/tests/setup.js src/tests/**/*.spec.js",
  }
}


三、執行
新增測試(範例請參考 Counter.spec.js)後,執行指令即可
npm run test


四、限制

1. 無法支援目前 vue 最新版本 3.2.37,發現底下錯誤訊息:

ReferenceError: SVGElement is not defined

2. 無法支援 SFC ,發現底下警告訊息:

[Vue warn]: Component is missing template or render function.


參考文件:


2022年6月8日 星期三

Github Action 自動部署 github-pages


Github pages 適合展示靜態頁面,只要在 github 建立 gh-pages 分支,可依據用戶名稱和repo名稱來開啟頁面。

https://[USER_NAME].github.io/[REPO_NAME]/

以這個專案為例

https://github.com/chenuin/JavaScript30

路徑會是

https://chenuin.github.io/JavaScript30/


使用 JamesIves/github-pages-deploy-action@v4.3.3 有兩個必填參數:

  • branch: 分支
  • folder: 目錄,.代表整個repo根目錄

參數詳細說明請參考這裡,在 repo 裡新增 github action (連結):

name: Github pages

on:
  # Triggers the workflow on push events but only for the "master" branch
  push:
    branches: master

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout 🛎️
        uses: actions/checkout@v3

      - name: Deploy 🚀
        uses: JamesIves/github-pages-deploy-action@v4.3.3
        with:
          branch: gh-pages
          folder: .
          token: ${{ secrets.GH_PAT }}

GH_PAT 設定方式,請先至 Settings => Developer settings => Personal access tokens (或下方連結),按右上角新增Token,scopes 可直接勾選 repo 並將Token複製。

https://github.com/settings/tokens


再到專案的 Settings => Secrets => Actions (或下方連結),按右上角新增,命名 GH_PAT 並將剛剛複製的Token貼上。

https://github.com/[USER_NAME]/[REPO_NAME]/settings/secrets/actions


EASY!!


相關文章:


2022年1月25日 星期二

js 單元測試套件 Macha+Chai (es6 語法 Babel 設定)

安裝

首先安裝 mocha (官網)和 chai (官網)

npm install mocha chai --save-dev

chai 是一種斷言庫(Assertion Library),mocha 不像是jest已經內建,可以自行決定要使用哪一種套件,chai是其中最常見的一種。

package.json加入測試指令

"scripts": {
  "test": "npx mocha"
}


設定 Babel

安裝 Babel,再來的說明都會直接使用es6的語法,如果不需要,可以略過這部分。

npm install @babel/core @babel/preset-env @babel/register --save-dev

接著在根目錄新增 babel.config.js

// babel.config.js

module.exports = {
    presets: [
        '@babel/preset-env',
    ],
};

接著在根目錄新增 .mocharc.jsspec是設定 mocha 執行測試的檔案,預設為 test/ ,這裡設定成自動讀取 src/test/ 底下所有以 spec.js 為結尾的檔案。

require可以接陣列設定所需的 module

// .mocharc.js

module.exports = {
    spec: ['src/test/*.spec.js'],
    require: ['@babel/register'],
};

.mocharc.js 是 mocha 執行時會自動讀取的設定檔,也支援json 或 yaml(說明),可以選擇喜歡的格式新增,設定檔的內容可以參考:https://github.com/mochajs/mocha/tree/master/example/config

設定參考資料:
https://github.com/mochajs/mocha-examples/tree/master/packages/babel



建立測試

新增一個簡單的測試

// src/test/array.spec.js

import chai from 'chai';

describe('Array', () => {
  describe('#indexOf()', () => {
    it('should return -1 when the value is not present', function() {
      chai.assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});

馬上執行試試看

npm run test

應該會看到下面的資訊,

> vue3-webpack5-template@1.0.0 test
> npx mocha


  Array
      #indexOf()
          should return -1 when the value is not present

1 passing (8ms)

完成第一個測試囉!



支援 async/await

請安裝套件

npm install @babel/plugin-transform-runtime --save-dev

把套件加到 babel.config.js的 plugin 設定

module.exports = {
    require: ['@babel/register'],
    plugins: ['@babel/plugin-transform-runtime'],
};


Root Hooks

mocha 提供的 hook 包含 before(), after(), beforeEach(), and afterEach(),從語意應該不難看出用途,前兩個只會執行一次,後兩個則是每項測試都會執行。

若要在所有的測試上加上 Hook,則是有這四種 beforeAll(), afterAll(), beforeEach(), and afterEach(),執行時機不變,請根據情境加上執行內容:

// src/test/hooks.js

export const mochaHooks = {
  beforeEach: () => {
    // do something before every test

  }
};

接著在 .mocharc.js 加上設定

module.exports = {
    spec: ['src/test/*.spec.js'],
    require: [
      '@babel/register',
      'src/test/hooks.js',
    ],
};

https://mochajs.org/#hooks
https://mochajs.org/#defining-a-root-hook-plugin



測試結果

mocha 是個可愛的名稱,測試結果也可以換成很多有趣的模式:

npx mocha --report landing

https://mochajs.org/#reporters



支援瀏覽器介面

加上指定的路徑執行下面的指令

npx mocha init [PATH]
  • index.html
  • mocha.css
  • mocha.js
  • test.spec.js

目錄底下會多了上述這些檔案,此時只要將 test.spec.js 加入你的測試,再重新整理 index.html,就能看到測試結果已經輸出在畫面上。


可以將 chai 加入 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Mocha</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="mocha.css" />
    <script src="https://unpkg.com/chai/chai.js"></script>
  </head>
  <body>
    <div id="mocha"></div>
    <script src="mocha.js"></script>
    <script>
      mocha.setup('bdd');
    </script>
    <script src="tests.spec.js"></script>
    <script>
      mocha.run();
    </script>
  </body>
</html>

再來可以直接將前面新增的 src/test/array.spec.js 內容貼過去,index.html 已經載入 mocha 和 chai ,記得把第一行的 import 拿掉。



2022年1月23日 星期日

webpack 常用 plugin 介紹 - HtmlWebpackPlugin 自動產生 Html


根據「[Vue.js] 如何建立 Vue3 + webpack5 專案範例」的內容,封裝時已經先建立目錄 dist/ ,新增 index.html,預先將 main.js 加到 script 中。

接著,以下要介紹 HtmlWebpackPlugin ,這個 webpack plugin 可以自動產生 Html,並自動將所有的 js 檔加入 script 中。下面的操作會用 [vue3-webpack5-template] 這個專案操作,可以先 clone下來並 npm install。

一、安裝
npm install html-webpack-plugin --save-dev


二、新增模板

新增 index.html ,並保留一些區域方便我們可以自訂。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>
            <%= htmlWebpackPlugin.options.title %>
        </title>
    </head>
    <body>
        <div id="<%= id %>"></div>
    </body>
</html>


三、新增 Webpack 設定

為了突顯 HtmlWebpackPlugin 功能的強大,首先刻意將輸出的 js 檔案名稱改為 [name].[contenthash].js,這時變得無法預期編譯後的檔案名稱。

再來將 HtmlWebpackPlugin 加入 plugin,完整檔案請點連結

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
  },

  ...

  plugins: [
    new HtmlWebpackPlugin({
      template: 'template/index.html',
      title: 'Getting Started',
      templateParameters: {
        id: 'app',
      },
    }),
  ],
};

上面共使用了三個參數:

1. template - 顧名思義是模板的路徑
2. title - html 檔案的 <title>
也說明為什麼在 index.html 有這一段

<%= htmlWebpackPlugin.options.title %>

3. templateParameters - 這裡傳入一個物件,將 id 訂為 app,因此模板這段程式碼,將會使用這裡的設定複寫

<div id="<%= id %>"></div>

若要了解更多參數的使用,可以參考文件



四、執行

執行下面的指令開始打包

npm run build

程式碼已經 push 到分支test-webpack-plugin,或者參考變更可以按這裡


2021年10月1日 星期五

如何將 Github 專案部屬到 Heroku (Creating a 'Deploy to Heroku' Button)

先前「[django] 將Django專案部署到Heroku」提到如何一步一步建立 Django 專案,並部屬到 Heroku。若是Github現有的專案已經滿足 Heroku 基本所需的設定,可以透過網頁操作,將現有專案快速地複製到 Heroku 上。

操作說明使用 heroku-startup-settings 這個專案 ,可以到 Github 查看完整的程式碼。首先,Github專案必須在根目錄先建立 app.json 這個檔案:

{
  "name": "Heroku startup settings",
  "description": "Getting started with Django project",
  "repository": "https://github.com/chenuin/heroku-startup-settings",
  "logo": "https://node-js-sample.herokuapp.com/node.png",
  "keywords": ["heroku", "python", "django"]
}
(app.json)

內容很好理解,檔案沒有必填的欄位,通常會寫namedescriptionlogo有助於其他人理解這個專案的內容或目的,更多的設定可以參考 app.json schema

其中設定環境參數 env 應該是最常使用的,可以依照需求調整部屬。


app.json 正確建立後,就可以開啟這個連結。
https://heroku.com/deploy?[REPO_WEB_URL]/tree/[BRANCH_NAME]
請替換專案的路徑和分支名稱,因此連結為:

接者可以在 README.md 新增這段文字,
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/chenuin/heroku-startup-settings/tree/master)

請記得替換成自己的連結,按鈕效果就像這樣:

Deploy

點選按鈕開啟連結並填寫專案名稱,按下「Deploy app」,就會自動在 Heroku 建立一個一樣的新專案。


相關文章:

[django] 將Django專案部署到Heroku

參考資料:

https://devcenter.heroku.com/articles/heroku-button https://devcenter.heroku.com/articles/app-json-schema

2021年8月17日 星期二

Github Actions 自動 Jekyll 專案部屬 Github Pages

自從完成「Travis CI 自動 Jekyll 專案部屬 Github Pages 完整範例」很久沒有更新 Github Pages,近期上傳時卻發現CI執行失敗,並不是腳本有問題或編譯過程有錯誤,而是request被拒,所以即使換了Github Token依舊無法解決。

直到我發現 Travis CI 帳戶設定突然多了「Plan」,有免費的方案可以選擇,選擇之後再讓Job重跑居然就成功了,所謂的免費方案是給 10000 available credits,每次執行Job時就會扣點直到用完為止,之後可以一次性購買或者選擇月費方案。


Github Actions 是 Github 內建的功能,可以定義Repo自動化、執行CI/CD相關工作,因此決定將 Travis CI 的功能由 Github Actions 取代,以下將說明如何移除 myblog 原本 .travis.yml 的設定 ,以 Github Actions 自動部屬至 Github Pages。


一、選擇 Workflow 建立方式

方法一:

在專案根目錄

新增目錄 .github/workflow/,並在 workflow/ 新增副檔名為 .yml的檔案。

方法二:

到 Github repo上設定

可更改檔名和底下的內容


二、新增 Workflow

name 命名,可自行決定名稱

name: website

on 必填的設定,Github Action提供各種事件供選擇觸發時機,這邊設定為 push 時執行,也可以針對多個事件指定分支。

# Triggered when code is pushed to any branch in a repository
on: push


# Or ....
on:
  # Trigger the workflow on push,
  # but only for the main branch
  push:
    branches:
      - main

jobs 接下來是最重要的部分,workflow是由一個或多的Job組成,預設情況下會同時執行,每個 Job 必須給一個唯一的 job_id,是由數字、字母或 _- 組成的字串,且字首只能由字母或是 _。因此我們第一個發布 - publish 的動作:

jobs:
  publish:

再來是 publish 內需要哪些設定:

runs-on 必填的設定,使用哪種機器執行 workflow,像是 Ubuntu、macOS、windows server等 Github 提供的虛擬環境。

runs-on: ubuntu-latest

steps 定義有哪些任務,Job 由一連串的任務組成,可以替任務命名,會在 Github 上顯示。


uses 指定動作(Action),通常是一些重複性的執行動作,被打包成一個套件,可以在這裡直接使用,更多相關的套件可以到 Github marketplace 搜尋 。底下使用的是checkout一個新的分支並安裝Ruby。

steps:
  # Reference the major version of a release
  - uses: actions/checkout@v2   # Downloads a prebuilt ruby
  - uses: ruby/setup-ruby@v1

run 在虛擬機器 shell 上執行 command-line

steps:
  - run: bundle install
  - run: chmod +x ./script/cibuild
  - run: ./script/cibuild

with 執行動作時可以加入參數,利用 github-pages 可以快速設定,我們指定將網站部署到 chenuin/chenuin.github.io 這個 repo 的 master 分支,需要上傳的目錄為 ./_site ,也就是Jekyll編譯好的檔案目錄。

steps:
  - uses: crazy-max/ghaction-github-pages@v2
    with:
      repo: chenuin/chenuin.github.io
      target_branch: master
      build_dir: ./_site
    env:
      GITHUB_TOKEN: ${{ secrets.GH_PAT }}

env 這裡分為 GITHUB_TOKENGH_PAT兩種,前者不需要任何設定、僅限於同一個 repo 內的操作,後者則是部署到其他 repo 使用的。(說明)

GH_PAT 設定方式,請先至 Settings => Developer settings => Personal access tokens (或下方連結),按右上角新增Token,scopes 可直接勾選 repo 並將Token複製。

https://github.com/settings/tokens


再到專案的 Settings => Secrets => Actions (或下方連結),按右上角新增,命名 GH_PAT 並將剛剛複製的Token貼上。

https://github.com/[USER_NAME]/[REPO_NAME]/settings/secrets/actions

關於 GITHUB_TOKEN 可以看這部影片了解更多:


完整檔案如下:

name: website

on: push

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: 2.6
      - name: Install dependencies
        run: bundle install
      - name: Before srcipt
        run: chmod +x ./script/cibuild
      - name: Srcipt
        run: ./script/cibuild
      - name: Deploy to GitHub Pages
        if: success()
        uses: crazy-max/ghaction-github-pages@v2
        with:
          repo: chenuin/chenuin.github.io
          target_branch: master
          build_dir: ./_site
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT }}

檔案異動內容已經上傳至 Github ,可點選連結查看。


三、查看執行結果

https://github.com/[USER_NAME]/[REPO_NAME]/actions



相關文章:

參考連結:


2021年8月15日 星期日

CloudCannon 支援 Jekyll 網站後台管理CMS系統

With CloudCannon as your Jekyll CMS, you will have all the tools you need to create amazing static websites.

CloudCannon 是線上網站後台管理CMS系統,可以作為 Jekyll、HUGO等後台管理,除了提供圖形化操作介面新增文章,自動發布、排程的設定,也有免費的網域名(Domain) .cloudvent.net供即時瀏覽。

先註冊或使用 Github/Gitlab/Bitbucket 帳號登入,可以匯入已有的專案並支援雙向的同步,現在馬上開始!



輸入專案名稱:



選擇Github的同步的專案及分支:



編譯類型為Jekyll,其他安裝、編譯參數也在這邊設定。



完成後,可以看到後台。



這個測試網站是公開的,可以加上 Settings => Authentication 改用帳密登入。更多功能請參考 CloudCannon 官方文件

2021年8月9日 星期一

[Vue.js] 如何建立 Vue3 + webpack5 專案範例

以下說明如何使用 webpack5 打包 Vue3 專案,若尚未安裝 webpack5,可以參考「webpack5 安裝及基礎教學」。


一、安裝

需要安裝的套件如下,特別需要注意的是,在 Vue3 裡支援副檔名 .vue 的 single-file components 的套件,從 vue-template-compiler 變成 @vue/compiler-sfc

  • vue
  • @vue/compiler-sfc
  • vue-loader
  • webpack
  • webpack-cli


請先新增專案,並在目錄內新增 package.json,並 npm 執行安裝。

{
  "name": "vue3-webpack5-template",
  "version": "1.0.0",
  "description": "vue3-webpack5-template",
  "private": true,
  "scripts": {
    "build": "webpack"
  },
  "author": "chenuin",
  "license": "ISC",
  "devDependencies": {
    "@vue/compiler-sfc": "^3.1.5",
    "vue-loader": "^16.1.2",
    "webpack": "^5.49.0",
    "webpack-cli": "^4.7.2"
  },
  "dependencies": {
    "vue": "^3.1.5"
  }
}

執行指令安裝:

npm install



二、設定打包的設定檔

首先針對 Vue 專案所設定的,Loader 可分為testloader,前者是定義哪些檔案需要處理,像這裡就是副檔名為 .vue 的檔案;後者則是使用哪一個套件處理 :

module: {
    rules: [
        {
            test: /\.vue$/,
            loader: 'vue-loader'
        },
    ],
},
plugins: [
    new VueLoaderPlugin(),
],

當專案內import vue 可以使用別名(alias): 

resolve: {
    alias: {
        vue: 'vue/dist/vue.esm-bundler.js',
    },
},

因此完整的 webpack.config.js 如下:

const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
        ],
    },
    resolve: {
        alias: {
            vue: 'vue/dist/vue.esm-bundler.js',
        },
    },
    plugins: [
        new VueLoaderPlugin(),
    ],
};



三、新增Entry, Ouput等內容

在目錄內 src/ 新增兩個檔案:

Vue3 主要元件 App.vue

<template>
  <div class="app">
    <p
      v-text="msg" />
  </div>
</template>

<script>
export default {
    name: 'App',
    setup() {
      return {
        msg: 'Hello World!',
      };
    },
};
</script>

新增 Entry File: index.js
設定別名的用途可以看第一行 import App from './App.vue';

import { createApp } from 'vue';
import App from './App.vue';

createApp(App)
    .mount('#app');


目錄 dist/ 則是新增 index.html,要注意的是先前 index.js 是綁定到 #app,所以 <div id="app"></div> 就是 vue render的地方。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Getting Started</title>
    </head>
    <body>
        <div id="app"></div>
        <script src="./main.js"></script>
    </body>
</html>

此時的專案架構應該會像是:

├── package.json
├── dist
│   └── index.html
└── src
    ├── App.vue
    └── index.js

專案已經上傳 Github [vue3-webpack5-template],可以下載使用。



四、執行

執行下面的指令開始打包

npm run build


完成後目錄 dist/ 下多了一個檔案 main.js,此時可以開啟 index.html ,看到 Hello World! 就代表打包成功囉!



2020年9月7日 星期一

Asciidoctor 專案使用 Travis CI 自動部屬程式範例


Asciidoctor可以轉成 HTML 格式,所以可以使用 Travis CI 自動將 progit book 專案上傳到 github pages。

一、新增 .travis.yml
先將專案編譯成 HTML 等,並將相關的檔案放到新建的目錄 /publc
script:
  - bundle exec rake book:build
  - mkdir public
  - cp progit.html public/index.html
  - cp progit.{pdf,epub} public/
  - cp -r images/ public/
接著是部屬的部分,目錄 /publc 就是我們要放在網頁上的資料,develop 則是我們目前的分支名稱:
deploy:
  provider: pages
  skip_cleanup: true
  github_token: $GITHUB_API_TOKEN
  local_dir: ./public
  on:
    branch: develop
.travis.yml 完整程式碼請參考[這裡],或到官網參考更多的設定參數。

二、設定 Github Token
請參考 [這裡] 第二步驟,按照方法在 Travis CI 新增環境變數 GITHUB_API_TOKEN

三、更新
Push 到遠端後後,等 2-3 分鐘 CI 完成,Repo會多一個分支 gh-pages ,裡面會有複製過去的首頁、圖片等資料,再到 github.io 打開頁面就能看到成果。 


Github Repo:

Github pages:


2020年6月25日 星期四

Travis CI 自動 Jekyll 專案部屬 Github Pages 完整範例


了解如何「[Github] 在github.io建立免費的網站」,搭配使用 Jekyll 可以讓部落格或靜態網站的撰寫更加便利,完成內容的更新後,可以透過指令編譯 _site 的目錄,轉成瀏覽器可讀的格式,最後將目錄上傳到web server。

這些流程可以使用 Travis CI 自動化,當 github repo 收到新的 Request時,自動編譯上傳到 github.io。 若未有 Jekyll 專案,請先參考「靜態網頁部落格工具 Ruby + Jekyll 安裝教學」,建立一個新專案。

一、新增編譯腳本
mkdir script
vim script/cibuild
script/cibuild 內容如下(參考檔案):
#!/usr/bin/env bash
set -e # halt script on error

JEKYLL_ENV=production bundle exec jekyll build
# bundle exec htmlproofer ./_site

二、新增 Travis CI 設定檔
.travis.yml 內容如下(參考檔案):
language: ruby
rvm:
- 2.6
script: ./script/cibuild
before_script:
- chmod +x ./script/cibuild
deploy:
  provider: pages
  skip_cleanup: true
  github_token: $GITHUB_TOKEN
  repo: chenuin/chenuin.github.io
  local_dir: ./_site
  target_branch: master
  on:
    branch: master
TOKEN 設定(參考)
  1. 開啟頁面 https://github.com/settings/tokens/new
  2. 填寫備註(可以自行決定),並選擇 public_repo
  3. 送出
將畫面顯示的 token 複製保存好,到 Travis CI 設定環境變數,新增一個參數 GITHUB_TOKEN,內容就是剛剛複製的這一串字串 。 

※操作畫面可參考「Travis CI 快速部屬 Jekyll + Asciidoctor」的第四步驟 - 新增 github token 。

三、上傳
git add .
git commit -m 'init commit'
git push origin master

專案連結: 


Travis CI 快速部屬 Jekyll + Asciidoctor

Github.io可以支援markdown,若要 asciidoctor 進行編輯,可以透過 Jeykll 在 github 上提供的專案,免去複雜的設定,快速完成布署。內容是參考 README,作業系統為 Ubuntu,統整成下面的步驟:

一、安裝

二、下載原始碼
請先 fork jekyll-asciidoc-quickstart ,再下載專案 jekyll-asciidoc-quickstart
git clone https://github.com/[github-account]/jekyll-asciidoc-quickstart

三、設定 Travis CI
Travic CI 先後推出 travis-ci.org、travis-ci.com,兩者的介面很相近,以下都是使用 travis-ci.com 進行操作。
請先到 github settings,將這個專案同步到 Travis CI上。 



 

四、新增 github token
  1. 開啟頁面 https://github.com/settings/tokens/new
  2. 填寫備註(可以自行決定),並選擇 public_repo
  3. 送出
請將畫面顯示的 token 複製保存好,一旦離開此頁面,就不會再看到這串 token。若遺失 token,只能再另外產生一組新的。
 


完成後,到 Travis CI 設定環境變數(Environment Variables) 
Name:  GH_TOKEN
Value: [token]  (剛剛在github複製的字串)

按下 Add 完成設定。 


 (連結參考 https://travis-ci.com/github/[github-account]/jekyll-asciidoc-quickstart/settings)
  
直接在網頁上新增更方便,原始文件提供的方法是安裝 travis 的套件,用指令加密 token 後,直接新增到 .travis.yml,也可以參考試試看。

五、編輯 .travis.yml
原始專案設定 rvm 版本已經太舊了,請把 2.2 改成 2.6,否則 CI 執行會失敗。
# .travis.yml
rvm:
  - 2.6
完整檔案請看: .travis.yml
git add .travis.yml
git commit -m 'update rvm version'

六、上傳
git push -u origin master
可以到 Travis CI 上確認執行結果,若正確設定的話,將自動把 master 的內容編譯後,自動上傳到分支 gh-pages 。 

開啟頁面 https://[github-account].github.io/jekyll-asciidoc-quickstart/ ,順利看到畫面就完成了。

完整專案範例


2020年5月28日 星期四

靜態網頁部落格工具 Ruby + Jekyll 安裝教學


一、安裝Ruby
作業系統為Ubuntu 20,指令如下:
sudo apt update
sudo apt install ruby-full build-essential zlib1g-dev
設定用戶的環境變數,應避免用root安裝Ruby Gems。
echo '# Install Ruby Gems to ~/gems' >> ~/.bashrc
echo 'export GEM_HOME="$HOME/gems"' >> ~/.bashrc
echo 'export PATH="$HOME/gems/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

二、安裝Jekyll
Ruby中使用Gem作為套件管理的工具,就像是python和pip的關係。安裝套件的方式 gem install [packageName]
gem install jekyll bundler

三、建立新專案
新增一個 myblog 的專案
jekyll new myblog
在目錄下應該會發現新的資料夾 /myblog,大致的內容可以參考一下。
├── 404.html
├── about.markdown
├── _config.yml
├── Gemfile
├── Gemfile.lock
├── index.markdown
├── _posts
│   └── 2020-05-27-welcome-to-jekyll.markdown
└── _site
    ├── 404.html
    ├── about
    ├── assets
    ├── feed.xml
    ├── index.html
    └── jekyll

四、開啟服務
進入目錄後,啟動伺服器,預設主機名稱localhost、埠號4000,可以根據需求設定:
cd myblog
bundle exec jekyll serve

// or you can ...
bundle exec jekyll serve --host=[ip address] --port=[port number]
瀏覽器開啟 http://localhost:4000 ,就可以看到預設的首頁,安裝就告一段落,可以開始進行開發。

2020年5月26日 星期二

Asciidoctor + VS Code安裝外掛套件快速開發、預覽功能


一、安裝套件
方法一
(1) 按快捷鍵 [ctrl] + [P]
(2) 輸入下面的指令:
ext install joaompinto.asciidoctor-vscode
(3) 按 [Enter] 送出



方法二
(1) [View] → [Extensions]


(2) 搜尋「AsciiDoc joaompinto」,找到後按綠色按鈕 Install




二、使用方式
打開AsciiDoc的檔案(.adoc, .ad, .asc, .asciidoc),按下快捷鍵 [ctrl]+[shift]+[v]




三、輸出HTML
快捷鍵 [ctrl]+[alt]+[s],自動在同一個目錄下產生相同檔名的 html 檔案。

參考資料:https://github.com/asciidoctor/asciidoctor-vscode


2020年3月31日 星期二

[Git] 手動安裝 git 2.6 + 新指令 sparse-checkout


sparse checkout 的功能可以讓使用者追蹤儲存庫裡特定的資料夾或檔案,不需要clone整個專案。新版本 git 2.6 有新指令 sparse-checkout 讓操作更簡單方便,關於 sparse-checkout 的設定方法可以參考「[Git] 如何使用 sparse checkout 下載 repository 內特定資料夾或檔案」進行操作,以下主要介紹如何手動安裝 git以及常用的 sparse-checkout 指令。

安裝

1. 安裝相關套件
安裝編譯 Git 所需的函式庫:curl, zlib, openssl, expat 和 libiconv
sudo apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \
  libz-dev libssl-dev

2. 下載 git 原始碼
先下載 git 原始碼,接著解壓縮並進入目錄。
wget https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.26.0.tar.gz
tar zxvf git-2.26.0.tar.gz
git-2.26.0
※如果需要其他 git 版本 [https://mirrors.edge.kernel.org/pub/software/scm/git/]

3. 編譯與安裝
編譯的時間稍微比較久
./configure --prefix=/usr \
            --with-gitconfig=/etc/gitconfig \
            --with-python=python3 && make
安裝
sudo make install

安裝後並沒有明顯的成功訊息,所以很難確定到底有沒有裝好,所以可以透過指令查看版本:
git --version
git version 2.26.0


指令說明

◆ sparse checkout 設定初始化
git sparse-checkout init
開啟設定之後,在目錄會自動新增檔案 sparse-checkout ,預設內容是:
/*
!/*/
代表根目錄內第一層內所有的檔案都列入追蹤;換句話說,根目錄裡任何資料夾內的檔案(包含資料夾)都會被忽略。

必須先確定檔案 .git/info/sparse-checkout 已經存在,使用下列的指令才不會報錯:
◆ 列出目前追蹤的檔案
git sparse-checkout list
◆ 新增指令資料夾或檔案
語法與 .gitignore 相似,最簡單是直接列出完整的檔案路徑,根據需求可以列出複雜的規則,像是追蹤特定的檔案附檔名,或是排除特定的項目。
git sparse-checkout add [folderPath/filePath]
◆ 更新及應用
將資料夾或檔案路徑規則寫入 sparse-checkout ,並馬上採用。
git sparse-checkout set [folderPath/filePath]
◆ 取消
git sparse-checkout disable

參考資料:
https://git-scm.com/download/linux
https://git-scm.com/book/zh-tw/v2/開始-Git-安裝教學
http://www.linuxfromscratch.org/blfs/view/svn/general/git.html

[Git] 如何使用 sparse checkout 下載 repository 內特定資料夾或檔案


一般下載專案的指令會將整個 repository 下載
git clone [URL]
有時候你只需要專案部分資料,git clone 無法只下載其中一個資料夾或檔案,但是 sparse checkout 可以達到!當專案非常龐大時,既能節省硬碟容量,也能提升工作效率。

1. 在現有資料夾中初始化倉儲
先決定要把資料放在哪個目錄,並執行初始化。
mkdir myproject
cd myproject
git init

2. 新增遠端版本庫
git remote add origin [URL]

3. 開啟 sparse checkout 設定
git config core.sparseCheckout true

4. 設定指定資料夾或檔案
根據你的需求,把資料夾或檔案的路徑寫進去。
方法一
echo "path/to/your/folder/" >> .git/info/sparse-checkout
echo "myFile.example" >> .git/info/sparse-checkout
方法二
vim .git/info/sparse-checkout
# .git/info/sparse-checkout
# Please list your directory and file path here
path/to/your/folder/
myFile.example

5. 取得儲存庫分支 master 的更新
最後一個步驟,git pull下載資料。
git pull origin origin master

2020年2月28日 星期五

[Git] 客製化Git Hooks管理專案



所謂的Git Hooks指的是以腳本等方式設定執行動作,當git指令執行時,會自動觸發這些腳本的機制,時機可能是在git指令之前或是之後。根據git指令又可以分為server side和client slide兩大類:commit和merge觸發的是client side,server side則是在網路上收到推上去的commit(pushed commit)。

hooks 存放在目錄 /.git/hooks/ 裡,執行 git init 初始化時,git自動在目錄裡產生一些shell script範本,你也可以用Ruby或python等實作。範例可以直接使用,但要記得把副檔名的 .sample 拿掉。



如果需要自己新建hook,請確認一下檔案的執行權限已經開啟。
chmod +x [filePath]

常見的Hooks
Client Side
以下為4個與commit相關的hook:
  • 在commit之前會執行 pre-commit,可以運用在執行功能驗證、單元測試或是coding style的檢查,若有任何錯誤發生時,這個commit會被捨棄不執行。也可以下指令 git commit --no-verify 略過hook的執行。
  • prepare-commit-msg,這個hook對於一般commit比較不實用,多在commit訊息模板、merge commit、squash commits、amended commits等自動產生commit訊息的類型。
  • commit-msg需要commit訊息的模板檔案路徑作為參數,如果錯誤發生,git會停止進行這個commit,來確保所有的commit訊息都符合需要的格式。
  • commit結束後,會執行 post-commit ,不需要任何參數,你可以用 git log -1 HEAD 來確認剛剛commit的內容,或者通知其他類似的訊息。


Server Side
  • server端收到push時,首先執行 pre-receive ,如果錯誤發生,所有的commit將不會被受理。可以用來檢查有沒有任何non-fast-forwards。
  • updatepre-receive 有點相似。
  • post-receive 會在整個push過程結束後執行,可以用來通知專案成員或是其他服務的更新等。這個hook不會影響push過程,但在hook執行完之前,用戶端和伺服器端會持續連線,因此要避免在腳本中執行時間較長的工作。

參考資料:
https://git-scm.com/book/zh-tw/v2/Customizing-Git-Git-Hooks

2019年4月21日 星期日

[Github] 在github.io建立免費的網站


Github提供免費的方式建立自己的網站,不過只限於靜態的網頁,適合寫個人履歷、部落格或網站作品的分享,設定方法如下:

步驟一、建立Repository
名稱為[USERNAME].github.io[USERNAME]請填入github的帳戶名稱。



步驟二、新增頁面
用command line方式進行說明
git clone https://github.com/[USERNAME]/[USERNAME].github.io
cd [USERNAME].github.io
vim index.html

內容可以自己決定
<!DOCTYPE html>
<html>
 <head>
  <title>Home</title>
 </head>
 
 <body>
  <h1>Welcome</h1>
  <p>This is my first page.</p>
 </body>
</html>


步驟三、更新
git add index.html
git commit -m "Initial commit"
git push -u origin master

最後打開瀏覽器就可以看到成果囉!
https://[USERNAME].github.io



除了[USERNAME].github.io以外Repository,其他也可以建立一個新的分支(branch),命名為gh-pages,透過github.io訪問這個專案,同時保持所有的專案維護的方便性。
https://[USERNAME].github.io/[REPO_NAME]


https://pages.github.com/

2018年11月18日 星期日

[Github] 用Django專案示範如何使用Travis CI自動測試


開始之前請先到Travis CI[官網]用Github帳號登入
同步github上的專案,並啟動需要測試的專案(Repository)!

請在根目錄新建檔案.travis.yml
使用語言為python,並用3.5和3.6版本。
language: python
python:
  - "3.5"
  - "3.6"

env則是設定這個腳本中的參數,後面install則是安裝這個專案所需的套件。
env:
  - DJANGO_VERSION=2.1
  - DJANGO_VERSION=2.1.2
# command to install dependencies
install:
  - pip install -q Django==$DJANGO_VERSION
  - pip install -r requirements.txt

針對這個專案我寫了一段測試(連結),script就是執行裡面預先寫好的元件測試。
script: python manage.py test

上傳Github後,可以看到測試的結果,我們分別設定了2個版本的python、2個版本Django,所以會產生4個執行結果,就不需要一一下載各個版本來進行測試囉!

如果測試成功會顯示passing,若失敗會顯示failing,我在readme.md加上的標誌方便知道結果,新增方法請參考下面:


完整檔案如下(連結):
# .travis.yml
language: python
python:
  - "3.5"
  - "3.6"
env:
  - DJANGO_VERSION=2.1
  - DJANGO_VERSION=2.1.2
# command to install dependencies
install:
  - pip install -q Django==$DJANGO_VERSION
  - pip install -r requirements.txt
# command to run tests
script: python manage.py test

完整專案請到Github(連結)下載。