tampermonkey 简单脚本开发

tampermonkey 简单脚本开发

 

其中build.js 主要是为了向打包后的js文件写入 UserScript 信息, 之所以不用 BannerPlugin 是因为这个插件中如果包含一些特殊(@ == 等)字符会转换为逗号...... 设置raw为false时是下面这种, 没法用.... 

 

浏览器调试

首先在 chrome://extensions 页面,把 tampermonkey 的【允许访问文件网址】勾上。

在 ==UserScript== 里添加 // @require file://d:a.js

这样相当于直接引入本地js, 开发过程中每次修改文件后需要手动刷新页面, 这样就能使用最新的代码.... 这个方式没法热更新, 不过对于一些简单的脚本已经够用了

 

webpack配置相当简单, 暂时没有加其他loader(甚至都可以不要)

const path = require("path");
module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "output.js",
    path: path.resolve(__dirname, "build")
  }
};

 

package中主要是脚本

{
  "name": "bilibili-capture",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "npx webpack -p && node ./bin/build",
    "dev": "npx webpack --watch -d"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10"
  }
}

 

build.js 打包完成后写入banner

const fs = require("fs")
const path = require("path")

const filePath = path.resolve(__dirname,"..","build/output.js")
// console.log(filePath)
let text = fs.readFileSync(filePath,"utf8")
// console.log(text)
const bannerPath = path.resolve(__dirname,"..","src/banner.txt")
let banner = fs.readFileSync(bannerPath,"utf8")
// console.log(banner)
let outputPath =  path.resolve(__dirname,"..","build/output.user.js")
fs.writeFileSync(outputPath,banner+text)
// console.log(banner+text)
console.log("build finished")