如何在npm发布自己的工具包
邵预鸿 Lv5

首先了解npm的两条命令

  • npm login 在本地电脑命令登录npm
  • npm publish 发布包到npm中

建立自己的工具包开始

  • npm init --y 初始化一个项目

  • 指定一个入口集成所有导入的模块 如App.js

    1
    2
    export * from './methods'; //数据处理类
    export * from './methods/axios.js'; //请求类
  • 在webpack.config.js配置

    output.library.type正式环境一定是module,开发环境为了调试可以指定为umd

    output.library.type === module时,需要配置experiments.outputModule为true 详见: https://webpack.docschina.org/configuration/output/#outputlibrarytype

    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
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const path = require('path');
    const TerserPlugin = require("terser-webpack-plugin");
    module.exports = env => {
    const library = {
    type: env.production ? 'module' : 'umd'
    };
    if (env.development) {
    library.name = 'methods'
    }
    const plugins = [];
    if (env.development) {
    plugins.push(new HtmlWebpackPlugin({
    template: './template/index.html'
    }))
    }
    return {
    entry: {
    main: './app.js',
    },
    experiments: {
    outputModule: env.production ? true : false,
    },
    output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
    clean: true,
    library
    },
    mode: env.production ? 'production' : 'development',
    plugins,
    module: {
    rules: [
    {
    test: /\.less$/,
    use: ['style-loader', 'css-loader', 'less-loader']
    }
    ]
    },
    devServer: {
    static: {
    directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    port: 9000,
    open: false,
    http2: true,
    },
    optimization: env.production ? {
    minimize: true,
    minimizer: [new TerserPlugin()],
    } : {},
    }
    }

github建立仓库

项目根目录创建一个.gitignore文件,文件内配置不被git监听的文件

1
node_modules/

npm关联github

通过在package.json中配置以下代码实现关联github

1
2
3
4
"repository": {
"type": "git",
"url": "https://github.com/Syh1996/js-methods-store.git"
},

http://server.yuhongshao.cn/static/yuhongshao/20220715101103.png

npm发布前调整

修改package.json中的几项配置

1
2
3
4
5
"main": "dist/main.js", //指向打包后的入口文件    npm i xxxx,而不用npm i /node_moduels/xxx/dist/app.js   引入具体地址
"keywords": [
"array"
], //搜索seo,利于别人能搜索到你的包
"version": "1.0.9", //版本号

通过webpack打包发布

webpack打包后,通过npm publish发布到npm上,发布时需要注意

  • 包名必须是唯一的,不能与npm已有的包重名
  • 每一次打包发布,需要修改版本号
  • 本文标题:如何在npm发布自己的工具包
  • 本文作者:邵预鸿
  • 创建时间:2022-07-15 10:07:20
  • 本文链接:/images/logo.jpg2022/07/15/如何在npm发布自己的工具包/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!