文件監(jiān)聽(tīng)的作用是為了實(shí)現(xiàn)自動(dòng)化,釋放雙手和精力,提高效率,讓開(kāi)發(fā)者更加關(guān)注于開(kāi)發(fā)。npm script 文件監(jiān)聽(tīng)和 grunt、gulp 功能類似。
自動(dòng)刷新,意思就是改動(dòng)文件保存后,頁(yè)面自動(dòng)刷新,減少日常開(kāi)發(fā)的操作。
代碼檢查的監(jiān)聽(tīng)和自動(dòng)化
代碼檢查工具 stylelint、eslint、jsonlint 這些對(duì) watch 支持很弱,所以就需要引入工具包 onchange
安裝命令依賴包
1
2
3
|
npm i onchange -D // 或 yarn add onchange -D |
編寫(xiě)命令
1
2
3
4
5
6
7
|
"scripts" : { "//watch" : "# 監(jiān)聽(tīng)" , "test" : "# 單元測(cè)試 \n cross-env NODE_ENV=test mocha tests/" , "watch:test" : "npm test -- --watch" , "watch:lint" : "onchange -i \"**/*.js\" \"**/*.less\" -- npm run lint:css" , "watch" : "npm-run-all --parallel watch:*" , } |
剖析命令
- 使用 \" 是為了實(shí)現(xiàn)跨平臺(tái)兼容;
- 使用了 **/* 匹配通配符;
- 參數(shù) -i 是讓 onchange 在啟動(dòng)時(shí)就運(yùn)行一次 -- 之后的命令;
執(zhí)行命令
1
|
npm run watch |
實(shí)現(xiàn)自動(dòng)刷新
本章主要說(shuō)的是livereload。
安裝命令依賴包
1
2
3
|
npm i livereload -D // 或 yarn add livereload -D |
編寫(xiě)命令
1
2
3
4
5
6
|
"scripts" : { "//livereload" : "# 自動(dòng)刷新" , "client" : "npm-run-all --parallel client:*" , "client:reload-server" : "livereload src/" , "client:static-server" : "http-server src/" } |
頁(yè)面添加連接 js 腳本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
// src /index .html <!DOCTYPE html> <html lang= "en" > < head > <meta charset= "UTF-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1.0" > <meta http-equiv= "X-UA-Compatible" content= "ie=edge" > <title>npm script< /title > <link rel= "stylesheet" href= "./index.css" rel= "external nofollow" > < /head > <body> <h1>你好,npm script< /h1 > <script> var ctx = '<script src="http://' + (location.host || 'localhost' ). split ( ':' )[0] + ':35729/livereload.js?snipver=1"></' + 'script>' ; document.write(ctx) < /script > < /body > < /html > /* src /index .css */ body { color: #fff; background-color: green; } |
總結(jié)
以上所述是小編給大家介紹的npm script 的文件監(jiān)聽(tīng)和自動(dòng)刷新的命令詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
原文鏈接:https://juejin.im/post/5cfb289be51d45777a12615e