webpack输出配置类型详解

112 阅读1分钟

最近在写一个npm包时发现新版本的webpack^5.58.1打包不再以AMD标准输出,需要单独配置:

module.exports = {
// … 
output: {
    library: {
        name: 'MyLibrary',
        type: 'var'
    }
  }, 
};

library中的type包括如下可选配置项:

'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'amd', 'umd', 'system'

var

var MyLibrary = _entry_return_;
// In a separate script with `MyLibrary` loaded…
MyLibrary.doSomething();

module

import MyLibrary from 'mylibrary'

assign

MyLibrary = _entry_return_;

assign-properties

MyLibrary = typeof MyLibrary === 'undefined' ? {} : MyLibrary;

this

this['MyLibrary'] = _entry_return_;
// 在一个单独的脚本中
this.MyLibrary.doSomething();
MyLibrary.doSomething();

window

window['MyLibrary'] = _entry_return_;
window.MyLibrary.doSomething();

self

var MyLibrary = _entry_return_;
// In a separate script with `MyLibrary` loaded…
MyLibrary.doSomething();

global

global['MyLibrary'] = _entry_return_;
global.MyLibrary.doSomething();

commonjs

exports['MyLibrary'] = _entry_return_;
require('MyLibrary').doSomething();

commonjs2

module.exports = _entry_return_;
require('MyLibrary').doSomething();

amd

define('MyLibrary', [], function () {
    return _entry_return_;
});

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['MyLibrary'] = factory();
  else root['MyLibrary'] = factory();
})(global, function () {
  return _entry_return_;
});
import * as MyLibrary from _entry_return_;

system

System.register([], function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
  return {
    execute: function () {
      // ...
    },
  };
});