qingfengmy-join1

``` src | |index.js |math.js webpack.config.js package.json ```

Usage no npm install needed!

<script type="module">
  import qingfengmyJoin1 from 'https://cdn.skypack.dev/qingfengmy-join1';
</script>

README

1. 基本目录

src |
    |index.js
    |math.js
webpack.config.js
package.json
// math.js
export function add(a, b) {
  return a + b;
}
// index.js
import * as math from "./math";

export default { math };
// webpack.config.js
const path = require("path");
module.exports = {
  entry: "./src/index.js",
  mode: "development",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "lib.js"
  }
};

打包yarn run build,生成lib.jsdist目录

// lib.js
(function(modules) {})

2. output.library/libraryTarget

需求:在 html 中使用

// webpack.config.js
output: {
    path: path.resolve(__dirname, "dist"),
    filename: "lib.js",
    library: "libmath"
}

上面的配置生效后打出的 lib 如下

var libmath = (function(modules) {})

可以在 html 中直接使用

console.log(libmath.default.math.add(1, 2));

library: 实际是 script 使用时的全局变量名,和他一起出现但有默认值的是 libraryTarget

libraryTarget: 如果不配置 library,就没有 libraryTarget;如果配置了 library,它的默认值就是 var,作用就是生成一个 var 变量。它还有很多值

var: 默认值 var libmath = (function(modules) {}) window: window['libmath'] = (function(modules) {}) global: window["libmath"] = (function(modules) {}) this: this['libmath'] = (function(modules) {}) assign: libmath = (function(modules) {}) amd: define("libmath", [], function() {}) commonjs: exports["libmath"] = (function(modules) {}) commonjs2: module.exports = (function(modules) {}) umd: 都支持

(function webpackUniversalModuleDefinition(root, factory) {
  if (typeof exports === "object" && typeof module === "object")
    module.exports = factory();
  else if (typeof define === "function" && define.amd) define([], factory);
  else if (typeof exports === "object") exports["libmath"] = factory();
  else root["libmath"] = factory();
})(window, function() {
  return /******/ function(modules) {};
});

3. 验证

var/window/global/this/assign 都已经验证过,这里验证剩下的几种。

commonjs

const libmath = require("../dist/lib");
console.log(libmath);

// 结果
{ libmath: Object [Module] { default: { math: [Object] } } }

commonjs2

const libmath = require("../dist/lib");
console.log(libmath);
// 结果
Object [Module] { default: { math: Object [Module] { add: [Getter] } } }

amd

使用 amd 标准需要引入 require 库

<script src="./require.js"></script>
<script src="../dist/lib.js"></script>
<script>
  require(["libmath"], function(libmath) {
    console.log(libmath);
  });
</script>

umd

node 下会报一个错,window 找不到,需要配置 globalObject,值为 this

output: {
    path: path.resolve(__dirname, "dist"),
    filename: "lib.js",
    library: "libmath",
    libraryTarget: "umd",
    globalObject: "this"
}

编译出的结果

(function webpackUniversalModuleDefinition(root, factory) {
    if(typeof exports === 'object' && typeof module === 'object')
        module.exports = factory();
    else if(typeof define === 'function' && define.amd)
        define([], factory);
    else if(typeof exports === 'object')
        exports["libmath"] = factory();
    else
        root["libmath"] = factory();
})(this, function() {})

4. 使用 lodash

// string.js
import _ from "lodash";
export function join(a, b) {
  return _.join([a, b], "-");
}

之前打包的大小是 5kb,加上 lodash 之后打包是 553kb

5. 打包不包括 lodash

externals: {
    lodash: "lodash"
}

6. 使用 libmath

简化代码,只留一个 join

// join.js
import lodash from "lodash";
export function join(arr) {
  console.log("arr", arr, lodash);
  return lodash.join(arr, "|");
}
<script src="https://cdn.bootcss.com/lodash.js/4.17.12-pre/lodash.js"></script>
<script src="../dist/lib.js"></script>
<script>
  console.log(qingfengmyjoin.default.join([1, 2]));
</script>

使用上面的代码,发现会报错,上面的打印发现 lodash 是空,打开 lodash.js 发现他添加的全局对象是_

 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
    // Expose Lodash on the global object to prevent errors when Lodash is
    // loaded by a script tag in the presence of an AMD loader.
    // See http://requirejs.org/docs/errors.html#mismatch for more details.
    // Use `_.noConflict` to remove Lodash from the global object.
    root._ = lodash;

    // Define as an anonymous module so, through path mapping, it can be
    // referenced as the "underscore" module.
    define(function() {
      return lodash;
    });
  }
  // Check for `exports` after `define` in case a build optimizer adds it.
  else if (freeModule) {
    // Export for Node.js.
    (freeModule.exports = lodash)._ = lodash;
    // Export for CommonJS support.
    freeExports._ = lodash;
  }
  else {
    // Export to the global object.
    root._ = lodash;
  }

我们打包时已经把 lodash 排除了,现在需要外部的 lodash,但是 script 标签这种形式引进了的 lodash 的真名是_,那就需要我们在 externals 中配置 root 的值是_

因为上面配置的是 umd,如果这里 lodash 单独配置的话,就需要全部配齐,否则 webpack 打包会报错。改成这样,再打包刷新 html 就 ok 了。

externals: {
    lodash: {
      commonjs: "lodash",
      commonjs2: "lodash",
      amd: "lodash",
      root: "_"
    }
}

7. 发布到 npm

// package.json
"name": "qingfengmy-join1",
"main": "dist/lib.js",