npm script 的文件监听和自动刷新

文件监听的做用是为了实现自动化,释放双手和精力,提升效率,让开发者更加关注于开发。npm script 文件监听和 grunt、gulp 功能相似。javascript

自动刷新,意思就是改动文件保存后,页面自动刷新,减小平常开发的操做。css

代码检查的监听和自动化

代码检查工具 stylelint、eslint、jsonlint 这些对 watch 支持很弱,因此就须要引入工具包 onchangehtml

安装命令依赖包

npm i onchange -D
// 或
yarn add onchange -D
复制代码

编写命令

"scripts": {
   "//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:*",
}
复制代码

剖析命令

  • 使用 \" 是为了实现跨平台兼容;
  • 使用了 **/* 匹配通配符;
  • 参数 -i 是让 onchange 在启动时就运行一次 -- 以后的命令;

执行命令

npm run watch
复制代码

实现自动刷新

本章主要说的是 livereloadjava

安装命令依赖包

npm i livereload -D
// 或
yarn add livereload -D
复制代码

编写命令

"scripts": {
    "//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">
</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;
}
复制代码

剖析命令

  • 启动静态文件服务,页面经过 http 方式访问文件资源;
  • 启动 liveload 服务,负责文件改动自动刷新,监听文件变化,告知链接改动文件的客户端;
  • 客户端页面 src/index.html 中添加的 js 脚本接收 livereload-server 的告知消息;

执行命令

npm run client
复制代码

而后打开浏览器访问:http://localhost:8081,接着修改 src/index.css 并保存,你会发现浏览器自动刷新了。git

你能够...

上一篇:npm script 命令补全的实现github

下一篇:npm script 复杂场景的应用npm

目录:npm script 小书json

相关文章
相关标签/搜索