文件監聽的作用是為了實現自動化,釋放雙手和精力,提高效率,讓開發者更加關注于開發。npm script 文件監聽和 grunt、gulp 功能類似。
自動刷新,意思就是改動文件保存后,頁面自動刷新,減少日常開發的操作。
代碼檢查的監聽和自動化
代碼檢查工具 stylelint、eslint、jsonlint 這些對 watch 支持很弱,所以就需要引入工具包 onchange
安裝命令依賴包
npm i onchange -D// 或yarn add onchange -D
編寫命令
"scripts": { "http://watch": "# 監聽", "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:*",}
剖析命令
執行命令
npm run watch
實現自動刷新
本章主要說的是livereload。
安裝命令依賴包
npm i livereload -D// 或yarn add livereload -D
編寫命令
"scripts": { "http://livereload": "# 自動刷新", "client": "npm-run-all --parallel client:*", "client:reload-server": "livereload src/", "client:static-server": "http-server src/"}
頁面添加連接 js 腳本
// 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 的文件監聽和自動刷新的命令詳解,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答