webpack+react+ts封裝

我們?cè)谏弦黄恼乱呀?jīng)介紹過使用rollpkg進(jìn)行打包發(fā)布,這篇我們介紹一下如何使用webpack進(jìn)行打包,畢竟在工作中,使用webpack的頻率更高;

首先初始化項(xiàng)目

npx create-react-app [project-name] --template typescript

src/文件夾新建 /packages 文件夾,也可以為其他名字,這個(gè)就是用來(lái)要發(fā)布的 npm包 內(nèi)容;

安裝 webpack 及 ts 相關(guān)依賴

npm install webpack ts-loader
  • 添加 webpack 打包相關(guān)內(nèi)容
  • 在根目錄新建 config 文件夾


    image.png

webpack.config.js

const { resolve } = require('path')

module.exports = {
  mode: 'production',
  entry: resolve(__dirname, '../src/packages/index.ts'),
  output: {
    filename: 'index.js',
    clean: true,
    library: {
      name: 'NpmName',
      type: 'umd',
    },
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: {
          loader: 'ts-loader',
          options: {
            configFile: resolve(__dirname, './tsconfig.json'),
          },
        },
      },
      {
        test: /\.(less|css)$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                javascriptEnabled: true,
              },
            },
          },
        ],
      },
      {
        test: /\.svg$/,
        use: [
          {
            loader: 'svg-sprite-loader',
            options: {
              symbolId: 'icon-[name]',
            },
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    alias: {
      '@': resolve(__dirname, '../src'),
    },
  },
}

package.json

{
  "name": "npm_name",
  "version": "0.1.0",
  "description": "",
  "main": "lib/index.js",
  "keywords": [],
  "author": "xiaohuihui",
  "license": "ISC",
  "publishConfig": {
    "registry": "xxx" // npm 發(fā)布地址
  }
}

package.js

const path = require('path')
const fse = require('fs-extra')
const webpack = require('webpack')
const chalk = require('chalk')
const Spinner = require('cli-spinner').Spinner
const shell = require('shelljs')

function pathResolve(dir) {
  return path.resolve(__dirname, dir)
}

var spinner = new Spinner(chalk.green('%s Packing...'))
spinner.setSpinnerString('????????')
spinner.start()

const tempJson = fse.readJsonSync(pathResolve('package.json'))

// 處理相關(guān)依賴
const devJson = fse.readJsonSync(pathResolve('../package.json'))
tempJson.peerDependencies = devJson.peerDependencies
tempJson.dependencies = devJson.dependencies
fse.emptyDirSync(pathResolve('../dist/lib'))
fse.outputJsonSync(pathResolve('../dist/package.json'), tempJson, {
  spaces: 2,
})

// 打包處理
const config = require(pathResolve('webpack.config.js'))
// eslint-disable-next-line no-unused-expressions
;(config.output.path = pathResolve('../dist/lib')),
  (config.externals = [
    ...Object.keys(tempJson.peerDependencies),
    ...Object.keys(tempJson.dependencies),
  ])

config.plugins = (config.plugins || []).concat([
  new webpack.ProgressPlugin((percentage, msg, ...args) => {
    spinner.setSpinnerTitle(
      chalk.green(
        '%s ' + parseInt(percentage * 100) + '% Packing... ' + (args[0] || '')
      )
    )
    if (percentage >= 1) {
      spinner.stop()
      process.stdout.write('\n')
    }
  }),
])

webpack(config, (err, stats) => {
  if (err) return console.error(err)
  if (stats.hasErrors()) {
    stats.toJson().errors.forEach((e) => console.error(e))
    console.error()
  } else {
    if (stats.hasWarnings()) {
      stats.toJson().warnings.forEach((w) => console.warn(w))
    }
    console.log(chalk.green('? Packing successfully'))
  }
})

tsconfog.json

{
  "compilerOptions": {
    "baseUrl": "../",
    "noImplicitAny": true,
    "module": "esnext",
    "declaration": true,
    "declarationDir": "../dist/lib",
    "target": "es5",
    "jsx": "react-jsx",
    "allowJs": true,
    "moduleResolution": "node",
    "noEmit": false,
    "allowSyntheticDefaultImports": true,
    "paths": {
      "@/*": ["src/*"]
    },
  },
  "include": [
    "../src/packages"
  ]
}

需要修改根目錄下 package.json 添加 peerDependencies

{
  ...
  "peerDependencies": {
    "react": "^18.1.0",
    "react-dom": "^18.1.0"
  },
  “scripts”: {
    ...
    "publish": "node ./config/package.js"
  }
}

現(xiàn)在我們就配置好了,當(dāng)我們需要打包時(shí)候,就可以 執(zhí)行 npm run publish 即可;
打完包,執(zhí)行 npm publish dist 即可發(fā)布到倉(cāng)庫(kù);

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、創(chuàng)建項(xiàng)目 npm v5.2.0引入的一條命令(npx),引入這個(gè)命令的目的是為了提升開發(fā)者使用包內(nèi)提供的命令行...
    三也視界閱讀 2,479評(píng)論 0 2
  • 目錄第1章 webpack簡(jiǎn)介 11.1 webpack是什么? 11.2 官網(wǎng)地址 21.3 為什么使用 web...
    lemonzoey閱讀 1,829評(píng)論 0 1
  • 構(gòu)建一個(gè)小項(xiàng)目——FlyBird,學(xué)習(xí)webpack和react。(本文成文于2017/2/25) 從webpac...
    布蕾布蕾閱讀 17,137評(píng)論 31 98
  • 1.webpack的概念 webpack是一個(gè)流行的前端項(xiàng)目構(gòu)建工具,可以解決目前web開發(fā)的困境。webpack...
    是培根不是培根閱讀 500評(píng)論 0 0
  • 1.webpack簡(jiǎn)介 1.1 webpack是什么? CommonJS和AMD是用于JavaScript模塊管理...
    淺笑6666閱讀 335評(píng)論 0 1

友情鏈接更多精彩內(nèi)容