当前位置:首页 > 通信资讯 > 正文

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

自动刷新,意思就是改动文件保存后,页面自动刷新,减少日常开发的操作。

代码检查的监听和自动化

代码检查工具 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": "# 监听", "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 在启动时就运行一次-- 之后的命令;

执行命令

?
1 npm run watch

实现自动刷新

本章主要说的是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 的文件监听和自动刷新的命令详解,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

原文链接:https://juejin.im/post/5cfb289be51d45777a12615e

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。