创建npm包 2个字符串数字相加_json

*package.json

{
  "name": "large-number",
  "version": "1.0.0",
  "description": "大整数加法打包",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "prepublish": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "terser-webpack-plugin": "^2.3.5",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11"
  },
  "dependencies": {
    "babel": "^6.23.0"
  }
}

* webpack.config.js

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    entry: {
        'large-number': './src/index.js',
        'large-number.min': './src/index.js'
    },
    output: {
        filename: '[name].js',
        library: 'largeNumber',
        libraryTarget: 'umd',
        libraryExport: 'export'
    },
    mode: "none",
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                include: '/\.min\.js$/'
            })
        ]
    }
};

// largeTarget.default

* src/index.js

/**
 * Created by mzh on 4/23/2020.
 */
export default function add(a, b) {
    let i = a.length - 1;
    let j = b.length - 1;

    let carry = 0;
    let ret = '';
    const CHAR_CODE_ZERO = '0'.charCodeAt(0);

    while (i>=0 || j >= 0) {
        let x = 0, y = 0;
        let sum = 0;

        if (i >= 0) {
            x = a[i].charCodeAt(0) - CHAR_CODE_ZERO;
            i -= 1;
        }
        if (j >= 0) {
            y = b[j].charCodeAt(0) - CHAR_CODE_ZERO;
            j -= 1;
        }
        sum = x + y + carry;

        if (sum > 9) {
            carry = 1;
            sum -= 10;
        } else {
            carry = 0;
        }
        // 0 + ''
        ret = String.fromCharCode(sum + CHAR_CODE_ZERO) + ret;
    }
    if (carry) {
        ret = String.fromCharCode(carry + CHAR_CODE_ZERO) + ret;
    }
    return ret;
}

// add("999", "1");
// add("1", "999");
// add("123", "321");
// add("999999999", "1");

* index.js

if (process.env.NODE_ENV == "production") {
    module.exports = require('./dist/large-number.min.js');
} else {
    module.exports = require('./dist/large-number.js');
}

 

npm run build

npm login

npm publish