Skip to content

Commit

Permalink
feat: rollup plugin 拓展配置
Browse files Browse the repository at this point in the history
  • Loading branch information
ahwgs committed May 7, 2021
1 parent 2931522 commit ecbc700
Show file tree
Hide file tree
Showing 16 changed files with 232 additions and 45 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ module.exports = {
'import/no-dynamic-require': 0,
'@typescript-eslint/indent': 0,
indent: 0,
'no-await-in-loop': 0,
},
}
39 changes: 38 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,31 @@ export default {

配置打包文件是否需要输出 `sourcemap` 文件

- **umd**

`umd` 只能使用 `rollup` 打包

- **umd.outFile**

输出文件,优先级大于上面的那个 `outFile`

- **umd.minify**

是否输出 `umd.min.js` 一般用于正式环境


- **umd.globals**

`umd` 全局模块, 官网解释 [rollup globals](https://www.rollupjs.com/guide/big-list-of-options#%E5%85%A8%E5%B1%80%E6%A8%A1%E5%9D%97globals--g--globals)

- **umd.name**

`umd` name 官网解释 [rollup name](hhttps://www.rollupjs.com/guide/big-list-of-options#%E7%94%9F%E6%88%90%E5%8C%85%E5%90%8D%E7%A7%B0name--n--name)

- **umd.sourcemap**

配置打包文件是否需要输出 `sourcemap` 文件

- **disableTypeCheck**

打包时禁用 `typescript` 类型检查
Expand All @@ -104,4 +129,16 @@ export default {

- **extraRollupPlugins**

拓展 `rollup plugins`
拓展 `rollup plugins`

- **include**

配置 `@rollup/plugin-commonjs` `include` 属性

- **extraReplacePluginOpts**

配置 `@rollup/plugin-replace` 属性

- **extraInjectPluginOpts**

配置 `@rollup/plugin-inject` 属性
7 changes: 5 additions & 2 deletions examples/sdk-demo/.avengerrc.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
export default {
esm: 'rollup',
cjs: 'rollup',
outFile: 'sdk-demo',
umd: false,
outFile: 'sdk',
umd: {
name: 'SDK',
sourcemap: true,
},
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./dist/sdk-demo.esm.js"></script>
<script src="./dist/sdk.esm.js"></script>
</head>
<body>
test page
Expand Down
14 changes: 14 additions & 0 deletions examples/sdk-demo/index.umd.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- <script src="./dist/sdk-demo.esm.js"></script> -->
<script src="./dist/sdk.umd.js"></script>
</head>
<body>
test page
</body>
</html>
9 changes: 6 additions & 3 deletions examples/sdk-demo/package.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
{
"name": "sdk-demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"build": "../../packages/cli/bin/avenger.js build",
"build:w": "../../packages/cli/bin/avenger.js build -w",
"dev": "parcel index.html"
"dev:umd": "parcel index.umd.html",
"dev:esm": "parcel index.esm.html"
},
"devDependencies": {
"@types/node": "^15.0.2",
"parcel-bundler": "^1.12.5",
"typescript": "^4.2.4"
},
"dependencies": {
"the-answer": "^1.0.0"
}
},
"module": "./dist/sdk.esm.js",
"main": "./dist/sdk.js"
}
8 changes: 7 additions & 1 deletion examples/sdk-demo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ const main = () => {
console.log('calc:', calc(1, 4))
console.log('ddd:', ddd('ddd123'))
console.log('foo:', foo)

console.log('process.env.NODE_ENV', process.env.NODE_ENV)
}

main()
export default {
init() {
main()
},
}
5 changes: 5 additions & 0 deletions examples/sdk-demo/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,11 @@
"@parcel/utils" "^1.11.0"
physical-cpu-count "^2.0.0"

"@types/node@^15.0.2":
version "15.0.2"
resolved "https://registry.yarnpkg.com/@types/node/-/node-15.0.2.tgz#51e9c0920d1b45936ea04341aa3e2e58d339fb67"
integrity sha512-p68+a+KoxpoB47015IeYZYRrdqMUcpbK8re/zpFB8Ld46LHC1lPEbp3EXgkEhAYEcPvjJF6ZO+869SQ0aH1dcA==

"@types/q@^1.5.1":
version "1.5.4"
resolved "https://registry.yarnpkg.com/@types/q/-/q-1.5.4.tgz#15925414e0ad2cd765bfef58842f7e26a7accb24"
Expand Down
2 changes: 2 additions & 0 deletions packages/config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@
"@osdoc-dev/avenger-utils": "^0.0.3",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-commonjs": "^18.0.0",
"@rollup/plugin-inject": "^4.0.2",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^11.2.1",
"@rollup/plugin-replace": "^2.4.2",
"@rollup/plugin-url": "^6.0.0",
"@svgr/rollup": "^5.5.0",
"babel-plugin-istanbul": "^5.2.0",
Expand Down
4 changes: 3 additions & 1 deletion packages/config/src/config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ const schema = createSchema(joi =>
minify: joi.boolean(),
sourcemap: joi.boolean(),
minFile: joi.boolean(),
name: joi.string().required(),
name: joi.string(),
globals: joi.object(),
}),
],
outFile: joi.string(),
entry: [joi.string()],
disableTypeCheck: joi.boolean(),
typescriptOpts: joi.object(),
include: joi.string(),
})
)

Expand Down
86 changes: 78 additions & 8 deletions packages/config/src/rollup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@
* @Author: ahwgs
* @Date: 2021-04-02 21:35:08
* @Last Modified by: ahwgs
* @Last Modified time: 2021-05-07 00:17:08
* @Last Modified time: 2021-05-08 00:20:06
*/
import path from 'path'
import { IRollupBuildOpt, IBuildConfigOpt, BundleOutTypeMap, IEsmOpt, ICjsOpt } from '@osdoc-dev/avenger-shared'
import { lodash, getExistFile, error, getPackageJson } from '@osdoc-dev/avenger-utils'
import {
IRollupBuildOpt,
IBuildConfigOpt,
BundleOutTypeMap,
IEsmOpt,
ICjsOpt,
IUmdOpt,
IPackageJson,
} from '@osdoc-dev/avenger-shared'
import { RollupOptions, OutputOptions } from 'rollup'
import { terser } from 'rollup-plugin-terser'
import url from '@rollup/plugin-url'
Expand All @@ -15,8 +24,9 @@ import json from '@rollup/plugin-json'
import babel, { RollupBabelInputPluginOptions } from '@rollup/plugin-babel'
import commonjs from '@rollup/plugin-commonjs'
import tempDir from 'temp-dir'
import { getExistFile, error } from '@osdoc-dev/avenger-utils'
import nodeResolve from '@rollup/plugin-node-resolve'
import replace, { RollupReplaceOptions } from '@rollup/plugin-replace'
import inject, { RollupInjectOptions } from '@rollup/plugin-inject'

interface IGetPluginOpt {
isTs: boolean
Expand All @@ -26,6 +36,9 @@ interface IGetPluginOpt {
extraRollupPlugins?: any[]
extensions?: string[]
extraNodeResolvePluginOpt: Object
include?: string
extraReplacePluginOpts?: Object
extraInjectPluginOpts?: Object
}

function getBablePluginOpt() {
Expand All @@ -45,6 +58,9 @@ function getPlugin(opt?: IGetPluginOpt) {
extraRollupPlugins,
extensions,
extraNodeResolvePluginOpt,
include = /node_modules/,
extraReplacePluginOpts,
extraInjectPluginOpts,
} = opt || {}

// 获取 @rollup/plugin-babel 配置
Expand Down Expand Up @@ -76,28 +92,38 @@ function getPlugin(opt?: IGetPluginOpt) {
]
: []

const hasReplace = extraReplacePluginOpts && Object.keys(extraReplacePluginOpts || {}).length > 0

const hasInject = extraInjectPluginOpts && Object.keys(extraInjectPluginOpts || {}).length > 0

return [
url(),
svgr(),
commonjs(),
commonjs({ include }),
nodeResolve({ mainFields: ['module', 'jsnext:main', 'main'], extensions, ...extraNodeResolvePluginOpt }),
...tsPlugin,
babel(babelPluOpt),
json(),
...(hasReplace ? [replace({ ...extraReplacePluginOpts } as RollupReplaceOptions)] : []),
...(hasInject ? [inject({ ...extraInjectPluginOpts } as RollupInjectOptions)] : []),
...extraRollupPlugins,
]
}

export const getRollupConfig = (opt: IRollupBuildOpt): RollupOptions => {
export const getRollupConfig = (opt: IRollupBuildOpt): RollupOptions[] => {
const { cwd, entry, type, buildConfig } = opt || {}
const {
esm,
cjs,
umd,
outFile,
disableTypeCheck = false,
extraTypescriptPluginOpt = {},
extraRollupPlugins = [],
extraNodeResolvePluginOpt,
extraReplacePluginOpts,
extraInjectPluginOpts,
include,
} = buildConfig as IBuildConfigOpt

const extensions = ['.js', '.jsx', '.ts', '.tsx', '.es6', '.es', '.mjs']
Expand All @@ -106,6 +132,8 @@ export const getRollupConfig = (opt: IRollupBuildOpt): RollupOptions => {
// 是否是ts
const isTypeScript = entryExt === '.ts' || entryExt === '.tsx'

const pkg = getPackageJson(cwd) as IPackageJson

if (isTypeScript) {
const tsConfigFile = getExistFile({
cwd,
Expand Down Expand Up @@ -144,19 +172,61 @@ export const getRollupConfig = (opt: IRollupBuildOpt): RollupOptions => {
extraRollupPlugins,
extensions,
extraNodeResolvePluginOpt,
include,
extraReplacePluginOpts,
extraInjectPluginOpts,
}

// umd 基础配置
const umdOutput = {
format: type,
sourcemap: umd && (umd as IUmdOpt).sourcemap,
file: path.join(cwd, `dist/${(umd && (umd as IUmdOpt).outFile) || `${outFileName}`}.umd.js`),
name: (umd && umd.name) || (pkg.name && lodash.camelCase(path.basename(pkg.name))),
globals: umd && (umd as IUmdOpt).globals,
}

switch (type) {
case BundleOutTypeMap.umd:
return { input }
return [
{
input,
output: { ...umdOutput },
plugins: [
...getPlugin(pluginOpt),
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
],
},
// xx.umd.min.js
...(umd && (umd as IUmdOpt).minFile
? [
{
input,
output: {
...umdOutput,
file: path.join(cwd, `dist/${(umd && (umd as IUmdOpt).outFile) || `${outFileName}`}.umd.min.js`),
},
plugins: [
...getPlugin(pluginOpt),
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
terser(terserOpts),
],
},
]
: []),
]
case BundleOutTypeMap.cjs:
output = {
format: type,
sourcemap: cjs && (cjs as ICjsOpt).sourcemap,
file: path.join(cwd, `dist/${(cjs && (cjs as ICjsOpt).outFile) || `${outFileName}`}.js`),
}
plugins = [...getPlugin(pluginOpt), ...(cjs && (cjs as ICjsOpt)?.minify ? [terser(terserOpts)] : [])]
return { output, input, plugins }
return [{ output, input, plugins }]
case BundleOutTypeMap.esm:
output = {
format: type,
Expand All @@ -165,7 +235,7 @@ export const getRollupConfig = (opt: IRollupBuildOpt): RollupOptions => {
}
// 压缩
plugins = [...getPlugin(pluginOpt), ...(esm && (esm as IEsmOpt)?.minify ? [terser(terserOpts)] : [])]
return { output, input, plugins }
return [{ output, input, plugins }]

default:
throw new Error(`Unsupported type ${type}`)
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @Author: ahwgs
* @Date: 2021-04-02 09:45:43
* @Last Modified by: ahwgs
* @Last Modified time: 2021-05-07 00:15:09
* @Last Modified time: 2021-05-07 23:21:08
*/
import path from 'path'
import {
Expand Down Expand Up @@ -54,5 +54,5 @@ export const build = (opt?: ICliOpt) => {
}

// build umd
if (umd && umd.name) rollupBuild({ cwd, type: BundleOutTypeMap.umd, entry, watch, buildConfig })
if (umd) rollupBuild({ cwd, type: BundleOutTypeMap.umd, entry, watch, buildConfig })
}
Loading

0 comments on commit ecbc700

Please sign in to comment.