How to build a npm library with webpack
What I will talk about
- directory configuration
- package.json
- how to export multiple modules
- how to build a UMD module
- how to deal with external dependencies
- using react and es6
Directory Config

Package.json
-
name
-
version
-
main
-
scripts
-
peerDependencies
-
git urls as dependencies
git+ssh://user@hostname:project.git#commit-ish
How to export multiple modules
Build a main entry file, such as Index.js, export multiple modules using ES6
import products from 'js/models/Products'
import productList from 'js/ProductList'
export const Products = products;
export const ProductList = productList;
export default ProductList;
How to build a UMD module
使用webpack的libraryTarget 功能 ,配置你的libraryTarget为’umd’, 这样就会让你的包同时支持AMD, COMMON JS 和script tags
output: {
filename: '[name].js',
path: '<%= config.distDir %>/js/',
library: ["LoanProductList", "[name]"],
libraryTarget: "umd"
}
How to deal with external dependencies
使用wenpack 的externals配置,以下的配置告诉webpack打包时,react, react-list, react-dom是外部依赖,就不用把这些库的代码打进我的库里
externals: [
"react",
"react-dom",
"react-list"
],
Using react and ES6
使用最新的babel(6.0及以上),需要如此配置
module: {
loaders: [
{
test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/,
query: {
presets: ['react','es2015']
}
}
]
},
或者写一个.babelrc文件,配置上解析react和ES的plugin
How to build an NPM package
By jingliu
How to build an NPM package
- 523