個人第一個 package

問,製做一個 package,總共須要幾步? 答:三步。html

前言

是的,這是一個孔子看了想打人,諸葛看了要罵街的答案。正經一點兒說,製做一個包裏面的細節仍是很多的。要求一個做者對 JavaScript 模塊化有基本的認識,不僅是像我同樣只熟悉 AMD, CMD, commonJS 的拼寫。最起碼要知道它們之間的區別和使用場景。其中,commonJS 是 node 服務端使用的,在瀏覽器中並不支持,前端可能會陌生。咱們簡單區分一下:module.exports/requireexport/import 分別是 node 和 ES 6 使用的規範。前端

起個名字

要製做一個 package 是要從 npm init 開始的。輸入這個命令後,會有一個交互式的問答操做,生成一份簡單的 package.json, 裏面包含一些基本信息。而後,須要註冊一個npm帳號,使用 npm login 來執行登錄操做。起名字是個簡單而又愉快的過程,接下來的製做,可就要花點心思了。node

如何製做

1.目錄結構

  • dist
  • doc
  • src
  • test

package 目錄的結構大體如此,按照需求來區分。咱們須要一個用來編寫 package 的源碼目錄 src。須要一個打包生成的目錄,供其餘人調用 dist,注意,這個dist的目錄也要在根目錄的 package.json 中設置 main.js 屬性。須要一個目錄來管理文檔說明,指引其餘人如何使用,這就是 doc 目錄,這個目錄其實是一個獨立的子 package,它包含本身獨立的 webpack.config.js,由於它通過 webpack 打包生成的文檔包含 html 文件,不僅是一個供用戶 import 的 package。react

2.webpack 配置

talk is cheap, show me your code. 說話是便宜的,看我你的代碼。(這個直譯辣不辣眼鏡)。接下來,打算在下面的實際配置中經過具體添加註釋來講明webpack

module.exports = {
  // 必定要使用 production 的配置項,由於這個包生成的文件是給其餘用戶使用的,production 提供了基本的壓縮優化功能,以及其餘一些不一樣的默認設置。
  "mode": "production",
  // 就是咱們的源碼目錄沒什麼多說的
  "entry": "./src/index.js",
  // 這裏須要自定義
  "output": {
    "path": __dirname + '/dist',
    "filename": "[name].js",
    // 這裏推薦使用 umd,畢竟考慮用戶會用 require 和 import 兩種方式導入咱們的包
    "libraryTarget": "umd"
  },
  "module": {
    // 慣例配置,無需多言
    "rules": [
      {
        "test": /\.(js|jsx)$/,
        "exclude": /node_modules/,
        "use": {
          "loader": "babel-loader",
        }
      }
    ]
  },
  externals: {
    // 這裏要格外注意,個人這個包基於 react 組件開發。這裏不須要包 react 打包進去,一個是由於體積,另外用戶必定要有 react 環境才能正常使用咱們的包。
    'react': "react"
  }

}
複製代碼

3.文檔編寫

前面提到文檔編寫的包實際上是一個獨立的 package,這裏也把配置代碼貼了出來。主要不一樣在於有 devsever 和 htmlWebpackPlugin。git

var path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development',
  entry: "./src/index.js",
  output: {
    filename: "index-bundle.js"
  },
  "module": {
    "rules": [
      {
        "test": /\.(js|jsx)$/,
        "exclude": /node_modules/,
        "use": {
          "loader": "babel-loader",
        }
      }
    ]
  },
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 9000,
    //module: false
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "doc.html",
      template: "./src/index.html"
    })
  ]
};

複製代碼

4.gitignore 和 .npmignore 等其餘設置

Keeping files out of your package

Use a .npmignore file to keep stuff out of your package. If there’s no .npmignore file, but there is a .gitignore file, then npm will ignore the stuff matched by the .gitignore file. If you want to include something that is excluded by your .gitignore file, you can create an empty .npmignore file to override it. Like git, npm looks for .npmignore and .gitignore files in all subdirectories of your package, not only the root directory.web

咱們能夠經過上述文檔知道一件事, npmignore 比 gitignore 的優先級高。npm

5.(誤)其餘重要的事

持續集成是開發一個包所必備的,由於我尚未具體實踐,這裏就挖坑不表了。json

參考資料

pic
相關文章
相關標籤/搜索