# library

npm init -y 
//math.js
export function add(a, b) {
	return a + b;
}

export function minus(a, b) {
	return a - b;
}

export function multiply(a, b) {
	return a * b;
}

export function division(a, b) {
	return a / b;
}
//string.js
import _ from 'lodash';

export function join(a, b) {
	return _.join([a, b], ' ');
}
//index.js
import * as math from './math';
import * as string from './string';

export default { math, string }
//webpack.config.js 
const path = require('path');

module.exports = {
	mode: 'production',
	entry: './src/index.js',
	externals: 'lodash',//避免多次引入lodash
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'library.js',
		library: 'library',//兼容script标签引入这个库
		libraryTarget: 'umd'//兼容es6和commonjs等模式,可以是'this','window'等参数
		// library: '[name]', // 整个库向外暴露的变量名
		// libraryTarget: 'window' // 变量名添加到哪个上 browser
		// libraryTarget: 'global' // 变量名添加到哪个上 node
		// libraryTarget: 'commonjs'
	}
}

webpack默认打包之后的代码形式是这样的(假设我导出 module.exports = 'hello world' )

(function () {
  return 'hello world'
})()

注意:代码是一个自执行函数,外界想获取函数里面的返回值怎么办(也就是模块的导出结果 hello world ),那么就需要配置一个 library

const path = require('path')

module.exports = {
  entry: './src/utils.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    library: 'result'
	// library: '[name]' //如果多入口,可以这样配置
  }
}

然后打包之后是这样的形式

var result = (function () {
  return 'hello world'
})()

通过把导出的结果赋值给 result 变量,配置了 library: 'result'

将打包之后的文件引入到HTML文件中,可以直接使用哦!(假设打包的文件名是bundle.js)

<body>
  <script src="./dist/bundle.js"></script>
  <script>
    console.log(result)
  </script>
</body>

如果你不想在HTML中使用,想在一个JS文件里面通过 require 导入来使用,需要这么配置

const path = require('path')

module.exports = {
  entry: './src/utils.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    libraryTarget: 'commonjs2'
  }
}

打包之后代码是这样的

module.exports = (function () {
  return 'hello world'
})()

可以在JS文件中导入来使用

import result from './bundle'

console.log(result)

同时支持import和require语法引入,两个配置同时使用,生效的是第二种模式。

# npm发布新包

  • 保证包名不重复(package.json中的那么)
  • npm adduser ,然后输入密码账号
  • npm publish,同时需要验证邮箱来发布
最后更新: 5/1/2023, 4:47:21 PM