2018年3月28日 星期三

Runtime + Compiler on Vue-Cli 3.0


有需求動態載入 component,
在 jsbin 做簡單的測試是沒問題,
但使用 Vue-Cli 3.0 的開發環境,
卻拋出以下錯誤

You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

經一番奮鬥後,發現 Vue-Cli 3.0 的 webpack 設定,
預設載入的 Vue 是 vue.runtime.esm.js,
所以在 runtime 的時候會發生此問題,
需將  vue.runtime.esm.js 換成  vue.esm.js
在 run time 期間也有 compiler 可以用

那該怎麼做呢?

在根目錄下設定 vue.config.js 如下即可
 (若沒有此檔,請自行新增!)
module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm.js'
      }
    }
  }
}


參考來源:

  1. https://github.com/vuejs/vue/tree/dev/dist#explanation-of-build-files
  2. https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md

2018年3月22日 星期四

關閉 Visual Studio 2017 自動編譯 ts 檔


在專案檔加入 <typescriptenabled>true</typescriptenabled>.

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
  </PropertyGroup>


reference:

TypeScriptCompileBlocked

If you are using a different build tool to build your project (e.g. gulp, grunt , etc.) and VS for the development and debugging experience, set true in your project. This should give you all the editing support, but not the build when you hit F5.

2017年12月14日 星期四

Startup pm2 command for Windows Server 2012 R2


需在 windows server 重新啟動的時候,
自動執行 pm2 start someapp.js,
pm2 有 startup command 提供此機制,但不支援 windows,
以下是 worked solution


The following is my latest solution which works really well:
  • create a specific Windows user for running node scripts
  • login as that user and npm install pm2 -g
  • pm2 start all the apps I would like to have startup
  • pm2 save to save the current process list
  • create a .bat file and within it paste the following commands:
@echo off
set HOMEDRIVE=C:
set HOMEPATH=\Users\%USERNAME%
set path=C:\Users\%USERNAME%\AppData\Roaming\npm;%path%
pm2 delete all & pm2 resurrect

Use Windows Task Scheduler to create a task that:
  • runs "whether user is logged on or not"
  • is Triggered "At startup"
  • is configured to run the .bat file that we created


2017年11月7日 星期二

How to enable hardware virtualization on a MacBook?

開發環境在 Mac 上的 windows 10 Home
需要啟用 virtualization ,
可是硬體本身有支援,卻沒有啟用 virtualization,
但是該如何啟用呢?
方式如下:

How to enable virtualization in Boot Camp.
  1. holding the option key on startup, boot in to OS X. 
  2. Then go to System Preferences 
  3. Startup Disk and choose your Boot Camp partition
  4. The computer will restart and boot into Windows, with virtualization enabled.

OK! 附張成功的圖紀念一下!

2017年11月1日 星期三

Error: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

使用 LinqToExcel 突然發生 error,原來是安裝 windows update 後,發生的慘案
Error: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

解決方案如下:

1. uninstall KB4041676 on Windows 10 and KB4041681 on Windows 7.

2. Find prior version (4.0.9801.0) of msexcl40.dll

3. Place in another directory. They suggest the application directory, but since in the next step you will modify registry to point to this older version, it can probably go anywhere.

4. Update registry key HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Jet\4.0\Engines\Excel\win32 to point to the location from step 2.

但此招是救急,可能有安全性的疑慮!

2017年10月16日 星期一

query pagination data with mongoose


目前透過 mongoose 查詢 pagination 資料覺得很麻煩,
先取得 total count 再取 page data,
目前使用的方式如下:

    user
        .find(where)
        .count()
        .then((totalCount) => {
            if (totalCount && totalCount > 0) {
                return user.find(where)
                    .select('field1 field2 field3 filed4')
                    .sort({ createdOn: -1 })
                    .skip(skip)
                    .limit(limit)
                    .exec()
                    .then((rows) => {
                        return {
                          rows:rows
                          totalCount: totalCount
                    });
            } else {
                 return res.status(200)
                        .json({
                         rows: [],
                         skip: skip,
                         limit: limit,
                         totalCount: 0
                        })
                        .end();
            }
        })
        .then((result) => {
                 return res.status(200)
                        .json({
                         rows: result.rows,
                         skip: skip,
                         limit: limit,
                         totalCount: result.totalCount
                        })
                        .end();
        })
        .catch((err) => {
            next(err);
        });

寫得落落長,太麻煩了,花了一些時間查查,有沒有什麼方便的方式
原來 mongoose 有 pagination plugin 可以用,真的是佛心來的,
使用方式如下:

Installation:
npm install mongoose-paginate

Usage:
var mongoose         = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
 
var schema = new mongoose.Schema({ /* schema definition */ });
schema.plugin(mongoosePaginate);
 
var Model = mongoose.model('Model',  schema); // Model.paginate() 

Model.paginate([query], [options], [callback])

所以上面的範例可以改成:
var where   = {};
var options = {
    select:   'field1 field2 field3 filed4',
    sort:     { createdOn: -1 },
    lean:     true,
    offset:   20, 
    limit:    10
};
user.paginate(where, options).then(function(result) {
    return res.status(200)
                        .json({
                         rows: result.docs,
                         skip: skip,
                         limit: limit,
                         totalCount: result.total
                        })
                        .end()
});

太好了,是不是簡單很多!

reference:https://www.npmjs.com/package/mongoose-paginate

Avoiding Callback Hell in Node.js - Promise


寫 nodejs 就會用到非同步的 callback
就會碰到所謂的「callback hell」的囧境
什麼是 callback hell? 如下所示:

doSomeAsyncFunc(function () {
  doSomeAsyncFunc(function () {
    doSomeAsyncFunc(function () {
      doSomeAsyncFunc(function () {
        doSomeAsyncFunc(function () {
          doSomeAsyncFunc(function () {
            doSomeAsyncFunc(function () {
              doSomeAsyncFunc(function () {
                doSomeAsyncFunc(function () {
                  // 我到底在第幾層地獄啊!?
              })
            })
          })
        })
      })
    })
  })
})



這樣光要看懂就很辛苦了,還要怎麼維護程式碼呢?

有幾種解決方式:

  1. async.waterfall
  2. promise
  3. async/await

上一篇介紹了 async.waterfall,現在來看看 Promise 如何使用

1. 先將 doSomeAsyncFunc 包裝成 promise 物件
doSomeAsyncFunc(function () {
  return new Promise(function(resolve, reject) {
    // do something, possibly async
    if (/* everythings fine */) {
      resolve(result);
    } else {
      reject(err);
    }
  });
}

2. 使用 primise.then 即可攤平 callback hell

var promise = doSomeAsyncFunc();
promise.then((result) => {
  // get result
  return '2';
}).then((result2) => {
  // get result2 ('2')
  return '3';
}).then((result3) => {
  // get result3 ('3')
}).catch((err) => {
  // error handling
});

3. 所以一開始的範例就可以改成:

var promise = doSomeAsyncFunc();
promise.then((result) => {
  // do something
  return doSomeAsyncFunc();
}).then((result) => {
  // do something
  return doSomeAsyncFunc();
}).then((result) => {
  // do something
  return doSomeAsyncFunc();
}).then((result) => {
  // do something
  return doSomeAsyncFunc();
}).then((result) => {
  // do something
  return doSomeAsyncFunc();
}).catch((err) => {
  // error handling
});

這樣就可以攤平可怕的 callback hell,回到地球表面囉!