npm 发布webpack插件 webpack-html-cdn-plugin

原创
01/26 22:45
阅读数 2.7K

初始化一个项目

npm init

 

切换到npm源

淘宝

npm config set registry https://registry.npm.taobao.org

npm

npm config set registry http://registry.npmjs.org 

登录

npm login

登录状态

npm who am i

 

简单的插件,  将cdn文件插入到html中

const flatMap = require("array.prototype.flatmap");


function getList(modules, key, type) {
  return flatMap(modules, i => typeof i === 'string' ? i : i[key])
    .filter(
      i => i && i.split(".").pop() === type
    );
}

class WebpackHtmlCdnPlugin {
  constructor(
    {
      modules = [],
      isDev = true
    }) {
    this.modules = modules;
    this.isDev = isDev;
  }

  apply(compiler) {
    console.log(compiler);
    compiler.hooks.compilation.tap("WebpackHtmlCdnPlugin", compilation => {
      compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tapAsync(
        "WebpackHtmlCdnPlugin",
        (data, callback) => {
          let key = this.isDev ? "dev" : "prod";
          const jsList = getList(this.modules, key, "js");
          const cssList = getList(this.modules, key, "css");
          data.assets.js = jsList.concat(data.assets.js);
          data.assets.css = cssList.concat(data.assets.css);
          // console.log(" data.assets.js", data.assets.js);
          // console.log(" data.assets.css", data.assets.css);
          callback(null, data);
        }
      );
    });
  }
}

module.exports = WebpackHtmlCdnPlugin;

 

package.json, 设置用户和发布仓库

{
  "name": "webpack-html-cdn-plugin",
  "version": "1.0.1",
  "description": "webpack cdn inject",
  "main": "./src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "publishConfig": {
    "registry": "http://registry.npmjs.org"
  },
  "keywords": [
    "webpack",
    "cdn"
  ],
  "author": "ahaoboy <504595380@qq.com>",
  "license": "ISC",
  "devDependencies": {
    "array.prototype.flatmap": "^1.2.3"
  }
}

发布, 修改后发布的话, 需要更新版本信息

npm publish

 

 

使用, 指定版本号安装, 默认会安装最新版

npm i webpack-html-cdn-plugin@1.0.1 -D
const WebpackHtmlCdnPlugin = require("webpack-html-cdn-plugin");

configureWebpack: {
  externals: {
    vue: "Vue"
  },
  plugins: [
    new WebpackHtmlCdnPlugin({
      modules: [
        {
          dev: ["https://unpkg.com/vue@2.6.11/dist/vue.js"],
          prod: ["https://unpkg.com/vue@2.6.11/dist/vue.min.js"]
        }
      ],
      isDev: process.env.NODE_ENV === "development"
    })
  ]
}

 

生产环境

开发环境

展开阅读全文
打赏
0
1 收藏
分享
加载中
阿豪boy博主
这都能上推荐, 可想而知osc已经水成啥样了.....
01/27 12:40
回复
举报
更多评论
打赏
1 评论
1 收藏
0
分享
返回顶部
顶部