Home  >  Article  >  Web Front-end  >  How to write node files into npm packages and publish them?

How to write node files into npm packages and publish them?

青灯夜游
青灯夜游forward
2021-09-15 10:13:311899browse

nodeHow to write files into npm packages? The following article will introduce to you how to copy the node file into an npm package and publish it. I hope it will be helpful to you!

How to write node files into npm packages and publish them?

Copy the node file into an npm package and publish it

npm plug-in release

Publishing npm is actually It's a very simple thing. I just forgot about it because I haven't released it for a long time, and I have to look it up online, so I wrote an article to record it. [Recommended learning: "nodejs Tutorial"]

Create a new file directory

  • Create a new directory and name it Any
  • Run the command to generate package.json
npm init --yes

Install dependencies

if The project also requires other dependencies, which can be installed through npm install xxx as during normal development. However, one thing to note here is the difference between -S, --save and --save-dev, because this is usually done when developing projects. There is no essential difference between the three, but there is still a difference when developing npm package

  • ##-S and --saveThe downloaded plug-in will be written to dependencies, and when we install the custom plug-in, it will be downloaded together
  • --save-dev The plug-in will be written to devDendencies. This is only used during development and will not be installed along with the custom plug-in.

Completepackage.json<span style="font-size: 16px;"></span>

There are several important information that must be filled in

  • name Others need to install this plug-in through npm install xxx, to install this xxx corresponds to the value# of name
  • ##version
  • The version of the plug-in, you need to re-release this version every time, otherwise the release will fail
  • main
  • Entry file
  • Others can be seen and need to be filled in
{
"name": "node-fs-copy", //发布的包名,默认是上级文件夹名。不得与现在npm中的包名重复。包名不能有大写字母/空格/下滑线!
  "version": "1.0.0",//你这个包的版本,默认是1.0.0。对于npm包的版本号有着一系列的规则,模块的版本号采用X.Y.Z的格式,具体体现为:
  1、修复bug,小改动,增加z。
  2、增加新特性,可向后兼容,增加y
  3、有很大的改动,无法向下兼容,增加x
  "description": "",
  "main": "index.js",//入口文件,默认是Index.js,可以修改成自己的文件,这个很重要,当你在实际项目使用的时候,let a = require("包名"),它就去会去找对应的文件路径哦。
  "scripts": {                  // 快捷命令,在package.json同目录下输入命令 npm run 键 就会执行 相对应的命令
    "bulid": "npx webpack --config myConfig.js"  //例如 输入 npm run bulid 就会执行npx webpack --config myConfig.js的命令 。
  },
  "keywords": [ // npm搜索的关键字
     "node",
     "fs",
     "copy"
  ],
  "publishConfig": {
    "registry": "" // 发布的npm地址
  },
  "repository": {
      "type": "git",
      "url": "git+https://github.com/xxxx" // 代码的git地址
  },
  "author": "zxw",
  "license": "ISC",//这个直接回车,开源文件协议吧,也可以是MIT,看需要吧。
  "dependencies": {             // 生产环境所依赖的包
    "jquery": "^3.4.1",
    "sea": "^1.0.2"
  },
  "devDependencies": {          // 开发环境所依赖的包
    "webpack": "^4.41.6"
  }
}

After confirming that the entry file is index.js, and writing the code, note that both introduction and export need to be done through node

index.js
  • const { exists, copyDir} = require(&#39;./lib/copy&#39;)
    
    const fsCopy = (sourcePath, deptPath)=> {
      exists(sourcePath,deptPath, copyDir)
    }
    
    module.exports = {
      fsCopy
    }
/lib/copy.js
  • const fs = require(&#39;fs&#39;)
    
    /**
     * 复制一个文件夹下的文件到另一个文件夹
     * @param src 源文件夹,即需要写出的文件
     * @param dst 目标文件夹,需要写入的文件
     */
    const copyDir = function (src, dst) {
      // 读取目录中的所有文件/目录
      fs.readdir(src, function (err, paths) {
        if (err) {
          throw err
        }
        paths.forEach(function (path) {
          const _src = src + &#39;/&#39; + path
          const _dst = dst + &#39;/&#39; + path
          let readable;
          let writable
          fs.stat(_src, function (err, st) {
            if (err) {
              throw err
            }
            // 判断是否为文件
            if (st.isFile()) {
              // 创建读取流
              readable = fs.createReadStream(_src)
              // 创建写入流
              writable = fs.createWriteStream(_dst)
              // 通过管道来传输流
              readable.pipe(writable)
            }
            // 如果是目录则递归调用自身
            else if (st.isDirectory()) {
              exists(_src, _dst, copyDir)
            }
          })
        })
      })
    }
    /*
    * 判断当前目标文件是否存在
    * 如若不存在需要先进行创建
    * */
    const exists = function (src, dst, callback) {
      // 如果路径存在,则返回 true,否则返回 false。
      if (fs.existsSync(dst)) {
        callback(src, dst)
      } else {
        fs.mkdir(dst, function () {
          callback(src, dst)
        })
      }
    }
    
    module.exports = {
      exists,
      copyDir
    }

TestThis piece I just conducted a relatively simple test, and I will add a dedicated chapter on plug-in testing later

Publish

Register npm account, usually npm can log in directly by associating with gitlab
  • Make sure your current image points to the npm image instead of the Taobao image. If you are not sure, you can directly execute
  • npm config set registry https://registry.npmjs.org/
and run Add user command, enter user, password, and email in sequence.
  • npm addUser

How to write node files into npm packages and publish them?

Make sure npm has executed the publish command while logged in in the browser
  • npm publish

How to write node files into npm packages and publish them?As shown in the picture, the release is successful.

Publish errorIf the release encounters a

403

error, it is very It is possible that the name field in your package name, i.e. package.json, is the same as the existing plugin name in npm. You need to modify it and re-publish itAfter modifying the name, an error still occurs,

You cannot publish over the previously published versions: xxx

, indicating that this version already exists in npm, and the version number needs to be modified

IterationIf there are any changes in the subsequent content, you need to manually change it every time you re-publish it

package.json/version

version number, and then execute the published command

Usage example

install

npm install node-fs-copy

In node code, local copy test

const { fsCopy } = require(&#39;node-fs-copy&#39;)
// 把内容从本地D盘的test/test目录,拷贝到test/test1目录
fsCopy(&#39;d:/test/test&#39;, &#39;d:/test/test1&#39;)

Server code copyLocal is There is no way to directly copy the server code. If you need to copy the server code, you need to meet a condition

The node server code and the file to be copied are on the same server
  • For example, the file address on the author's server is
/data/code-generator

, and the node service is also deployed in another directory on the same server <pre class="brush:js;toolbar:false;">//在服务器上运行,表示把服务器的/data/code-generator文件内的内容,拷贝到当前项目的./temporary/test内 fsCopy(&amp;#39;/data/code-generator&amp;#39;, &amp;#39;./temporary/test&amp;#39;)</pre>After completing the copy, you can use the packaging plug-in Compress the content into

zip package

, output it to the front end, then delete the temporary file ./temporary/test, and then delete the zip package<h2><strong>附上常用命令</strong></h2><pre class="brush:js;toolbar:false;">npm init --yes(初始化配置) npm i (会根据package.json里面的键dependencies,devDependencies来安装相对应的包) npm i 包(默认安装一个最新的包,这个包在node_modules文件夹里面,并且会更新在你的package.json文件) npm i 包@3.0.0(安装一个指定版本的包,会更新在你的package.json文件) npm i 包 --save-dev(安装一个开发环境所需要的包,会更新在你的package.json文件) npm uninstall 包(卸载一个包,会更新在你的package.json文件) npm update 包(更新此包版本为最新版本,会更新在你的package.json文件) npm run 脚本键(会根据package.json里面的&quot;scripts&quot;里面的脚本键自动执行相对于的值) npm publish (根据package.json的name发布一个包) npm unpublish 包名 --force(卸载npm网站上自己上传的包)</pre><p>更多编程相关知识,请访问:<a href="//m.sbmmt.com/course.html" target="_blank" textvalue="编程视频">编程视频</a>!!<br></p>

The above is the detailed content of How to write node files into npm packages and publish them?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete