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",
},