文件監(jiān)聽的作用是為了實現(xiàn)自動化,釋放雙手和精力,提高效率,讓開發(fā)者更加關注于開發(fā)。npm script 文件監(jiān)聽和 grunt、gulp 功能類似。
自動刷新,意思就是改動文件保存后,頁面自動刷新,減少日常開發(fā)的操作。
代碼檢查的監(jiān)聽和自動化
代碼檢查工具 stylelint、eslint、jsonlint 這些對 watch 支持很弱,所以就需要引入工具包 onchange
安裝命令依賴包
1
2
3
|
npm i onchange -D // 或 yarn add onchange -D |
編寫命令
1
2
3
4
5
6
7
|
"scripts" : { "//watch" : "# 監(jiān)聽" , "test" : "# 單元測試 \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:*" , } |
剖析命令
- 使用 \" 是為了實現(xiàn)跨平臺兼容;
- 使用了 **/* 匹配通配符;
- 參數(shù) -i 是讓 onchange 在啟動時就運行一次 -- 之后的命令;
執(zhí)行命令
1
|
npm run watch |
實現(xiàn)自動刷新
本章主要說的是livereload。
安裝命令依賴包
1
2
3
|
npm i livereload -D // 或 yarn add livereload -D |
編寫命令
1
2
3
4
5
6
|
"scripts" : { "//livereload" : "# 自動刷新" , "client" : "npm-run-all --parallel client:*" , "client:reload-server" : "livereload src/" , "client:static-server" : "http-server src/" } |
頁面添加連接 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; } |
總結
以上所述是小編給大家介紹的npm script 的文件監(jiān)聽和自動刷新的命令詳解,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
原文鏈接:https://juejin.im/post/5cfb289be51d45777a12615e