node的require

node的require

这里是谈js的require
require('xxx')
一开始是没有缓存的,第一次require('xxx')会将函数执行然后将模块(路径)缓存。
如果xxx中有 未声明的变量直接赋值 这相当于在浏览器中这么做。
结果是 该未声明的变量成为了顶级对象的属性(global对象,在浏览器中则是window对象)

如果用到了严格模式"use strict"(严格模式需要在函数内最开头声明,也就是文件xxx的最顶端)
可以用Function("r", "regeneratorRuntime = r")(runtime);来规避

如 npm的regenerator-runtime

"use strict"
/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var runtime = (function (exports) {
    /* ... */
}(
  // If this script is executing as a CommonJS module, use module.exports
  // as the regeneratorRuntime namespace. Otherwise create a new empty
  // object. Either way, the resulting object will be used to initialize
  // the regeneratorRuntime variable at the top of this file.
  typeof module === "object" ? module.exports : {}
));

try {
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
  console.log(accidentalStrictMode)
  // This module should not be running in strict mode, so the above
  // assignment should always work unless something is misconfigured. Just
  // in case runtime.js accidentally runs in strict mode, we can escape
  // strict mode using a global Function call. This could conceivably fail
  // if a Content Security Policy forbids using Function, but in that case
  // the proper solution is to fix the accidental strict mode problem. If
  // you've misconfigured your bundler to force strict mode and applied a
  // CSP to forbid Function, and you're not willing to fix either of those
  // problems, please detail your unique predicament in a GitHub issue.
  Function("r", "regeneratorRuntime = r")(runtime);
}

参考

  1. 深入理解node中require的原理及执行过程
posted @ 2020-04-30 12:16  菜鸡_chicken  阅读(448)  评论(0编辑  收藏  举报