我使用 webpack 打包代码
使用三方模块的时候发现, 直接 require node_modules
目录下的三方模块, 可以正常加载. 但是将该模块拷贝到其他目录后, 无法正常载入.
通过包名+文件名导入三方库, 和直接通过路径导入三方库有什么区别?
三方该模块的头部是这么写的, 似乎是为了兼容 AMD 和 CommonJS
(
function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(
[], function () {
return (
root['Autolinker'] = factory()
);
}
);
}
else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
}
else {
root['Autolinker'] = factory();
}
}(
this, function () {
如果将这个三方包拷贝到工程的目录中. 编译后的结果会是
/***/ },
/* 628 */
/***/ function(module, exports, __webpack_require__) {
省略
(function (root, factory) {
if (true) {
// AMD. Register as an anonymous module unless amdModuleId is set
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
省略
} else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object') {
省略
} else {
省略
}
})(undefined, function () {
也就是这个立即函数的参数this
变成了 undefined
. 如果是直接以包名形式导入则不会``
/***/ },
/* 1354 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) {
if (true) {
// AMD. Register as an anonymous module unless amdModuleId is set
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return (root['Autolinker'] = factory());
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
root['Autolinker'] = factory();
}
}(this, function () {