前言
目录结构
src目录放组件
example目录放调试例子
构建
使用webpack构建,分两个打包文件
example目录下起开发服务dev-server
配置没什么特别的,配了lessloader ,css,urlloader支持图片,eslint,用awesome-typescript-loader
解析ts。
根目录下打包出要发布的文件
配置output
libraryTarget:'commonjs2',
library:'Juno'
这里需注意output的libraryTarget,它决定webpack输出的暴露方式:
-
var 暴露为一个变量—-
var Juno = '''
-
暴露给全局对象:this, window,global —-
window.Juno = .....
-
commonjs用于commonjs环境 —
exports['Juno'] = ...
-
commonjs2 用于commonjs2 —
module.exports = ...
这里涉及commonjs和commonjs2的区别:
CommonJs spec defines only
exports
. Butmodule.exports
is used by node.js and many other CommonJs implementations.commonjs
mean pure CommonJscommonjs2
also includes themodule.exports
stuff. -
amd 暴露为AMD模块 —
define('Juno', [], function() { return _entry_return_; });
- umd 暴露为所有以上
- jsonp 包裹在jsonp容器中—
Juno(...)
组件库使用commonjs标准发布。
配置externals
使用webpack-node-externals
插件排除打包时候的所有依赖。
externals:[nodeExternals()]
注意因为组件中使用到了antd,有两个问题:
-
需要添加peerDependencies告知使用方组件库有对antd的依赖
npm会在安装结束后检查本次安装是否正确,如果不正确会给用户打印警告提示。
2.组件库中引入antd组件时候应动态加载,使用
import Alert from 'antd/es/alert';
方式,或者用babel-import-plugin。否则会导致使用方的动态加载失效,antd会全部打包。
支持treeShaking
webpack对esmodule默认支持tree shaking,所以打包输出esmodule就可以,然而webpack的output不能输出esmodule(webpack5貌似可以~)。所以使用gulp打出esmodule代码放到es目录中(业务方也会打包为什么不直接复制一份就行?因为考虑到使用方可能exclude:/node_moduel/
,所以避免es6代码不可正常使用)。配置package.json:
"main": "dist/main.js",
"module": "es/index.js",
"files": [
"dist",
"es"
],
三个字段的区别:
- main为入口文件,
require('juno')
或者import('juno')
时候就会找到main下的文件 - module用来指定esmodule的入口文件,如果两个字段存在会优先使用module,未找到文件再使用main
Babel.config.js:
['@babel/preset-env',
{
modules: false,
}
]
因为 tree-shaking 是依赖 ES Module 的静态加载,而 babel-presets-env 中是包含
ES2015 modules to CommonJS transform
的 plugin,也就是转化成 CommonJS,所以无法识别哪些代码是未引用的,也就是无法 tree-shaking,所以 babel transform 的时候应该保留 ES Module。
gulp配置
ts->js->es5
Less->css
输出es文件夹:
打出之后使用方引用时默认开启treeshaking
开发
本地调试组件时候直接起dev server调试src/components下的文件。
当需要调试在项目中使用组件是否成功时候有两方法:
npm link
在组件库下执行npm link
,组件库会被链接到全局,再到使用组件库的项目中npm link juno
就可以正常使用组件库了。
然后再package.json里配置一个watch命令,使用watch模式时,每次修改代码自动打包一次,生成新的dist文件,并直接映射项目的node_modules/juno下面
git
在项目的packagejson中这样配置
"dependencies": {
"public": "git://github.com/user/repo.git#ref",
"private": "git+ssh://git@github.com:user/repo.git#branch"
}
每次提交代码分支代码之后可以调试。
发布
未完。。。