RollUp實(shí)現(xiàn)ES打包,發(fā)布組件庫到NPM

Rollup是什么?

首先我們項(xiàng)目中常用的是webpack,因?yàn)轭愃朴赾reate-react-app自帶的都是webpack打包,用Rollup官網(wǎng)的話說 : Rollup的設(shè)計(jì)目標(biāo)是將JavaScript模塊打包成更小、更高效的輸出文件。它專注于ES6模塊的支持。 并且Tree Shaking功能,也是Rollup最早支持的,并且也是默認(rèn)開啟的, 隨后webpack進(jìn)行更新也支持了Tree Shaking。 總而言之, 就是類似于組件庫,公共函數(shù)庫等我們可以優(yōu)先選擇Rollup , 因?yàn)闀?huì)更輕量。 webpack就是更靈活,插件市場更豐富。

首先我們需要在根目錄創(chuàng)建rollup.config.js文件

大家也可以看出來rollup個(gè)人感覺配置還是比較簡單的

import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import scss from 'rollup-plugin-scss';
import { terser } from  'rollup-plugin-terser';

const overrides = {
  exclude: ['src/**/*.stories.tsx', 'src/**/*.test.tsx', 'setupTests.ts'],
};

const config = {
  input: 'src/index.tsx',
  output: {
    file: 'dist/index.js',
    format: 'es',
    sourcemap: true,
    inlineDynamicImports: true,
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    json(),
    typescript({ tsconfigOverride: overrides }),
    scss({
      fileName: 'index.css',
    }),
    terser(),
  ],
  external: ['react', 'react-dom'],
};

export default config;

因?yàn)轫?xiàng)目使用的是ts,所以我也附上tsconfig.json文件

{
  "compilerOptions": {
    "declaration": true,
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}

最后配置package.json文件,注意要指定files和main地址, files代表上傳那個(gè)文件到npm,main意思是從那個(gè)入口文件進(jìn)去。

  "name": "liyu-component",
  "author": {
    "name": "liyu",
    "email": "liyu990205@gmail.com"
  },
  "files": [
    "dist/*"
  ],
  "main": "dist/index.js",
  "version": "0.1.1",
  "scripts": {
    "build": "rollup --c",
  },

先執(zhí)行npm login, 登陸成功后, 最后執(zhí)行npm publish,就可以成功把npm庫發(fā)布到npm上了。

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

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

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