uni-app 項目使用 npm 包中的小程序自定義組件


原理

1. postinstall 時將 `node_modules` 下的小程序組件包復制到 `wxcomponents` 目錄下

2. 第三方包建議只用 `package.json` 管理,所以將代碼加入 .gitignore 中

 

核心代碼

// scripts/pkg-copy.js
//
本腳本用於將原生 npm 組件復制到 wxcomponents 文件夾 const fs = require('fs-extra') const path = require('path') // 需要復制的包 const pkgList = [ { from: 'some-mp-component/miniprogram_dist', to: 'my-mp-component' } ] const npmPath = path.join(__dirname, '../node_modules') const distPath = path.join(__dirname, '../src/wxcomponents') function copyPkg (pkg) { const from = `${npmPath}/${pkg.from}` const to = `${distPath}/${pkg.to}` fs.copySync(from, to) }

 

然后在 package.json 配置 postinstall 命令。這樣在 npm install 之后就會自動復制該包到 `wxcomponents`

  "scripts": {
    "postinstall": "node scripts/pkg-copy"
  },

配置 .gitignore

src/wxcomponents/my-mp-component

 

總結

簡單的使用第三方 npm 包配置就完成了,注意此種方法只適用於第三方包的自定義組件的 json 文件中沒有其他依賴的情況下。

如果需要處理有其他依賴的小程序自定義組件,需要考慮依賴解析的方案。

 

筆者也在研究這塊,可以繼續關注本博客哦~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM