猫码让前端飞Web前端之路

panda-utils:构建发布一个自己的函数库

2020-03-27  本文已影响0人  ComfyUI

如何构建一个libray库?构建完后怎么发布到npm让大家都可以用到?为什么要构建发布一个自己的函数库?本章就是想谈下这些问题。
webpack从0到1
panda-utils

1、缘起

2、开始

$ npm init -y
$ npm install webpack webpack-cli --save-dev
  panda-utils
+ |- build
+   |- webpack.common.js
+   |- webpack.dev.js
+   |- webpack.prod.js
+ |- /src
+   |- index.js
  |- package.json
  |- LICENSE
  |- README.md

3、webpack公共配置

var path = require("path");

module.exports = {
  entry: "./src/index.js",

  output: {
    path: path.resolve(__dirname, "../dist"),
    filename: "panda-utils.js",
    library: "pandaUtils",
    libraryTarget: "umd"
  }
};
# 安装babel相关,处理js
$ npm install @babel/core @babel/preset-env babel-loader babel-plugin-add-module-exports --save-dev

# 安装clean插件,打包前删除dist文件夹
$ npm install clean-webpack-plugin --save-dev

3、生产环境配置

# 合并webpack配置的插件
$ npm install webpack-merge --save-dev
const merge = require("webpack-merge");
const commonConfig = require("./webpack.common.js");

const prodConfig = {
  mode: "production",
  devtool: "cheap-module-source-map"
};

module.exports = merge(commonConfig, prodConfig);

4、开发环境配置

$ npm install webpack-dev-server html-webpack-plugin --save-dev
const merge = require("webpack-merge");
const commonConfig = require("./webpack.common.js");
const HtmlWebpackPlugin = require("html-webpack-plugin");

const devConfig = {
  mode: "development",

  devtool: "source-map",

  devServer: {
    contentBase: "./dist",
    port: "8080",
    open: true,
    hot: true
  },

  plugins: [
    // 可以为你生成一个HTML文件
    new HtmlWebpackPlugin({
      title: "webpack从0到1"
    })
  ]
};

module.exports = merge(commonConfig, devConfig);

5、发布

# 登录
$ npm login

# 查看当前镜像源
npm config get registry

# 如果是淘宝镜像源,需要设置到官方
$ npm config set registry https://registry.npmjs.org

# 发布
$ npm publish --access public

# 删除(只能删除24小时内publish的包)
$ npm unpublish <name>

6、小结

上一篇下一篇

猜你喜欢

热点阅读