rollup + typescript 构建 ts 包
2020-10-14 本文已影响0人
copyLeft
安装依赖
- rollup 打包工具
- rollup-plugin-node-resolve 依赖引入插件
- rollup-plugin-commonjs commonjs 转换
- rollup-plugin-eslint eslint 校验
- rollup-plugin-typescript2 ts 转换
- @typescript-eslint/parser eslint ts 解析器
- typescript ts解析器
rollup 配置
import path from 'path'
import resolve from 'rollup-plugin-node-resolve' // 依赖引用插件
import commonjs from 'rollup-plugin-commonjs' // commonjs模块转换插件
import { eslint } from 'rollup-plugin-eslint' // eslint插件
import ts from 'rollup-plugin-typescript2'
const getPath = _path => path.resolve(__dirname, _path)
import packageJSON from './package.json'
const extensions = [
'.js',
'.ts',
'.tsx'
]
// ts
const tsPlugin = ts({
tsconfig: getPath('./tsconfig.json'), // 导入本地ts配置
extensions
})
// eslint
const esPlugin = eslint({
throwOnError: true,
include: ['src/**/*.ts'],
exclude: ['node_modules/**', 'lib/**']
})
// 基础配置
const commonConf = {
input: getPath('./src/index.ts'),
plugins:[
resolve(extensions),
commonjs(),
esPlugin,
tsPlugin,
]
}
// 需要导出的模块类型
const outputMap = [
{
file: packageJSON.main, // 通用模块
format: 'umd',
},
{
file: packageJSON.module, // es6模块
format: 'es',
}
]
const buildConf = options => Object.assign({}, commonConf, options)
export default outputMap.map(output => buildConf({ output: {name: packageJSON.name, ...output}
typescript配置 tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"outDir": "./lib", // 输出目录
"sourceMap": false, // 是否生成sourceMap
"target": "esnext", // 编译目标
"module": "esnext", // 模块类型
"moduleResolution": "node",
"allowJs": false, // 是否编辑js文件
"strict": true, // 严格模式
"noUnusedLocals": true, // 未使用变量报错
"experimentalDecorators": true, // 启动装饰器
"resolveJsonModule": true, // 加载json
"esModuleInterop": true,
"removeComments": false, // 删除注释
"declaration": true, // 生成定义文件
"declarationMap": false, // 生成定义sourceMap
"declarationDir": "./lib/types", // 定义文件输出目录
"lib": ["esnext", "dom"], // 导入库类型定义
"types": ["node"] // 导入指定类型包
},
"include": [
"src/*" // 导入目录
]
eslint 配置 .eslintrc.js
const path = require('path')
const resolve = _path => path.resolve(__dirname, _path)
const DOMGlobals = ['window', 'document']
const NodeGlobals = ['module', 'require']
module.exports = {
env: {
browser: true,
es6: true
},
parser: '@typescript-eslint/parser', // 配置ts解析器
parserOptions: {
project: resolve('./tsconfig.json'),
tsconfigRootDir: resolve('./'),
sourceType: 'module'
},
// plugins: ['prettier'],
rules: {
'indent': ['error', 2],
'no-unused-vars': 'error',
'no-restricted-globals': ['error', ...DOMGlobals, ...NodeGlobals],
'no-console': 'off',
}
};
package.json
{
"main": "lib/index.js",
"module": "lib/index.esm.js",
"scripts": {
"dev": "set NODE_ENV=developemnt&& rollup -c rollup.config.js -w",
"build": "rm -fr lib && set NODE_ENV=production&& rollup -c rollup.config.js"
},
"types": "lib/index.d.ts", // 指定类型定义文件
...
}