1,自己打包的库无别的库引入时候
webpack.config.js
const path = require('path')
module.exports = {
mode: 'production',
devtool: 'cheap-module-source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.js',
library: 'library', // 配置这里 支持script标签引入
libraryTarget: 'umd' // umd支持通用的模块化引入方法(cmd、amd、esmodule)
}
}
引入方法:
//模块化引入(或者cmd,amd等方式引入)
import library from 'library'
/*也可在html中用script标签引入*/
<script src="library.js"></script>
2, 如果自己打包的库还引用了别的库的话,这时候打包的库不应该将别的库也打包进去,这样会增加代码体积和导致库重复引入的问题。
webpack.config.js
const path = require('path')
module.exports = {
mode: 'production',
devtool: 'cheap-module-source-map',
entry: './src/index.js',
// externals配置 表示不需要打包进库里的外库
// externals: ["lodash"], // 这个表示任何引入模式下名字都叫做lodash,推荐用这个配置
externals: {
lodash: {
root: '_', // 如果这个外库是全局引入的,那么他的变量名必须是_才行
commonjs:'lodash' // 如果这个外库在commonjs环境下被引用,这个lodash名字必须被起成lodash 例: const lodash = require('lodash')
}
}
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.js',
library: 'library', // 配置这里 支持script标签引入
libraryTarget: 'umd' // umd支持通用的模块化引入方法(cmd、amd、esmodule)
}
}
引入方式
import lodash from 'lodash' // 这个是library依赖的库
import library from 'library'