探索 Node.js 源码,详解cjs 模块的加载过程

探索 Node.js 源码,详解cjs 模块的加载过程

相信大家都知道如何在 Node 中加载一个模块:

const fs = require('fs');const express = require('express');const anotherModule = require('./another-module');

没错,require 就是加载 cjs 模块的 API,但 V8 本身是没有 cjs 模块系统的,所以 node 是怎么通过 require找到模块并且加载的呢?【相关教程推荐:nodejs视频教程】      

我们今天将对 Node.js 源码进行探索,深入理解 cjs 模块的加载过程。我们阅读的 node 代码版本为 v17.x:

git head :881174e016d6c27b20c70111e6eae2296b6c6293代码链接:github.com/nodejs/node…

源码阅读

内置模块

为了知道 require 的工作逻辑,我们需要先了解内置模块是如何被加载到 node 中的(诸如 ‘fs’,’path’,’child_process’,其中也包括一些无法被用户引用的内部模块),准备好代码之后,我们首先要从 node 启动开始阅读。node 的 main 函数在 [src/node_main.cc](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main.cc#L105) 内,通过调用方法 [node::Start](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L1134) 来启动一个 node 实例:

int Start(int argc, char** argv) {  InitializationResult result = InitializeOncePerProcess(argc, argv);  if (result.early_return) {    return result.exit_code;  }  {    Isolate::CreateParams params;    const std::vector* indices = nullptr;    const EnvSerializeInfo* env_info = nullptr;    bool use_node_snapshot =        per_process::cli_options->per_isolate->node_snapshot;    if (use_node_snapshot) {      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();      if (blob != nullptr) {        params.snapshot_blob = blob;        indices = NodeMainInstance::GetIsolateDataIndices();        env_info = NodeMainInstance::GetEnvSerializeInfo();      }    }    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);    NodeMainInstance main_instance(&params,                                   uv_default_loop(),                                   per_process::v8_platform.Platform(),                                   result.args,                                   result.exec_args,                                   indices);    result.exit_code = main_instance.Run(env_info);  }  TearDownOncePerProcess();  return result.exit_code;}

这里创建了事件循环,且创建了一个 NodeMainInstance 的实例 main_instance 并调用了它的 Run 方法:

int NodeMainInstance::Run(const EnvSerializeInfo* env_info) {  Locker locker(isolate_);  Isolate::Scope isolate_scope(isolate_);  HandleScope handle_scope(isolate_);  int exit_code = 0;  DeleteFnPtr env =      CreateMainEnvironment(&exit_code, env_info);  CHECK_NOT_NULL(env);  Context::Scope context_scope(env->context());  Run(&exit_code, env.get());  return exit_code;}

Run 方法中调用 [CreateMainEnvironment](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L170) 来创建并初始化环境:

Environment* CreateEnvironment(    IsolateData* isolate_data,    Local context,    const std::vector& args,    const std::vector& exec_args,    EnvironmentFlags::Flags flags,    ThreadId thread_id,    std::unique_ptr inspector_parent_handle) {  Isolate* isolate = context->GetIsolate();  HandleScope handle_scope(isolate);  Context::Scope context_scope(context);  // TODO(addaleax): This is a much better place for parsing per-Environment  // options than the global parse call.  Environment* env = new Environment(      isolate_data, context, args, exec_args, nullptr, flags, thread_id);#if HAVE_INSPECTOR  if (inspector_parent_handle) {    env->InitializeInspector(        std::move(static_cast(            inspector_parent_handle.get())->impl));  } else {    env->InitializeInspector({});  }#endif  if (env->RunBootstrapping().IsEmpty()) {    FreeEnvironment(env);    return nullptr;  }  return env;}

创建 Environment 对象 env 并调用其 [RunBootstrapping](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L398) 方法:

MaybeLocal Environment::RunBootstrapping() {  EscapableHandleScope scope(isolate_);  CHECK(!has_run_bootstrapping_code());  if (BootstrapInternalLoaders().IsEmpty()) {    return MaybeLocal();  }  Local result;  if (!BootstrapNode().ToLocal(&result)) {    return MaybeLocal();  }  // Make sure that no request or handle is created during bootstrap -  // if necessary those should be done in pre-execution.  // Usually, doing so would trigger the checks present in the ReqWrap and  // HandleWrap classes, so this is only a consistency check.  CHECK(req_wrap_queue()->IsEmpty());  CHECK(handle_wrap_queue()->IsEmpty());  DoneBootstrapping();  return scope.Escape(result);}

这里的 [BootstrapInternalLoaders](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L298) 实现了 node 模块加载过程中非常重要的一步:通过包装并执行 [internal/bootstrap/loaders.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L326) 获取内置模块的 [nativeModulerequire](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L332) 函数用于加载内置的 js 模块,获取 [internalBinding](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L164) 用于加载内置的 C++ 模块,[NativeModule](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L191) 则是专门用于内置模块的小型模块系统。

function nativeModuleRequire(id) {  if (id === loaderId) {    return loaderExports;  }  const mod = NativeModule.map.get(id);  // Can't load the internal errors module from here, have to use a raw error.  // eslint-disable-next-line no-restricted-syntax  if (!mod) throw new TypeError(`Missing internal module '${id}'`);  return mod.compileForInternalLoader();}const loaderExports = {  internalBinding,  NativeModule,  require: nativeModuleRequire};return loaderExports;

需要注意的是,这个 require 函数只会被用于内置模块的加载,用户模块的加载并不会用到它。(这也是为什么我们通过打印 require('module')._cache 可以看到所有用户模块,却看不到 fs 等内置模块的原因,因为两者的加载和缓存维护方式并不一样)。

用户模块

接下来让我们把目光移回到 [NodeMainInstance::Run](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L127) 函数:

int NodeMainInstance::Run(const EnvSerializeInfo* env_info) {  Locker locker(isolate_);  Isolate::Scope isolate_scope(isolate_);  HandleScope handle_scope(isolate_);  int exit_code = 0;  DeleteFnPtr env =      CreateMainEnvironment(&exit_code, env_info);  CHECK_NOT_NULL(env);  Context::Scope context_scope(env->context());  Run(&exit_code, env.get());  return exit_code;}

我们已经通过 CreateMainEnvironment 函数创建好了一个 env 对象,这个 Environment 实例已经有了一个模块系统 NativeModule 用于维护内置模块。然后代码会运行到 Run 函数的另一个重载版本:

void NodeMainInstance::Run(int* exit_code, Environment* env) {  if (*exit_code == 0) {    LoadEnvironment(env, StartExecutionCallback{});    *exit_code = SpinEventLoop(env).FromMaybe(1);  }  ResetStdio();  // TODO(addaleax): Neither NODE_SHARED_MODE nor HAVE_INSPECTOR really  // make sense here.#if HAVE_INSPECTOR && defined(__POSIX__) && !defined(NODE_SHARED_MODE)  struct sigaction act;  memset(&act, 0, sizeof(act));  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {    if (nr == SIGKILL || nr == SIGSTOP || nr == SIGPROF)      continue;    act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL;    CHECK_EQ(0, sigaction(nr, &act, nullptr));  }#endif#if defined(LEAK_SANITIZER)  __lsan_do_leak_check();#endif}

在这里调用 [LoadEnvironment](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/api/environment.cc#L403)

MaybeLocal LoadEnvironment(    Environment* env,    StartExecutionCallback cb) {  env->InitializeLibuv();  env->InitializeDiagnostics();  return StartExecution(env, cb);}

然后执行 [StartExecution](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L455)

MaybeLocal StartExecution(Environment* env, StartExecutionCallback cb) {  // 已省略其他运行方式,我们只看 `node index.js` 这种情况,不影响我们理解模块系统  if (!first_argv.empty() && first_argv != "-") {    return StartExecution(env, "internal/main/run_main_module");  }}

StartExecution(env, "internal/main/run_main_module")这个调用中,我们会包装一个 function,并传入刚刚从 loaders 中导出的 require 函数,并运行 [lib/internal/main/run_main_module.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/main/run_main_module.js) 内的代码:

'use strict';const {  prepareMainThreadExecution} = require('internal/bootstrap/pre_execution');prepareMainThreadExecution(true);markBootstrapComplete();// Note: this loads the module through the ESM loader if the module is// determined to be an ES module. This hangs from the CJS module loader// because we currently allow monkey-patching of the module loaders// in the preloaded scripts through require('module').// runMain here might be monkey-patched by users in --require.// XXX: the monkey-patchability here should probably be deprecated.require('internal/modules/cjs/loader').Module.runMain(process.argv[1]);

所谓的包装 function 并传入 require,伪代码如下:

(function(require, /* 其他入参 */) {  // 这里是 internal/main/run_main_module.js 的文件内容})();

所以这里是通过内置模块require 函数加载了 [lib/internal/modules/cjs/loader.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L172) 导出的 Module 对象上的 runMain 方法,不过我们在 loader.js 中并没有发现 runMain 函数,其实这个函数是在 [lib/internal/bootstrap/pre_execution.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/pre_execution.js#L428) 中被定义到 Module 对象上的:

Imagine By Magic Studio Imagine By Magic Studio

AI图片生成器,用文字制作图片

Imagine By Magic Studio 79 查看详情 Imagine By Magic Studio

function initializeCJSLoader() {  const CJSLoader = require('internal/modules/cjs/loader');  if (!noGlobalSearchPaths) {    CJSLoader.Module._initPaths();  }  // TODO(joyeecheung): deprecate this in favor of a proper hook?  CJSLoader.Module.runMain =    require('internal/modules/run_main').executeUserEntryPoint;}

[lib/internal/modules/run_main.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/run_main.js#L74) 中找到 executeUserEntryPoint 方法:

function executeUserEntryPoint(main = process.argv[1]) {  const resolvedMain = resolveMainPath(main);  const useESMLoader = shouldUseESMLoader(resolvedMain);  if (useESMLoader) {    runMainESM(resolvedMain || main);  } else {    // Module._load is the monkey-patchable CJS module loader.    Module._load(main, null, true);  }}

参数 main 即为我们传入的入口文件 index.js。可以看到,index.js 作为一个 cjs 模块应该被 Module._load 加载,那么 _load干了些什么呢?这个函数是 cjs 模块加载过程中最重要的一个函数,值得仔细阅读:

// `_load` 函数检查请求文件的缓存// 1. 如果模块已经存在,返回已缓存的 exports 对象// 2. 如果模块是内置模块,通过调用 `NativeModule.prototype.compileForPublicLoader()`//    获取内置模块的 exports 对象,compileForPublicLoader 函数是有白名单的,只能获取公开//    内置模块的 exports。// 3. 以上两者皆为否,创建新的 Module 对象并保存到缓存中,然后通过它加载文件并返回其 exports。// request:请求的模块,比如 `fs`,`./another-module`,'@pipcook/core' 等// parent:父模块,如在 `a.js` 中 `require('b.js')`,那么这里的 request 为 'b.js',           parent 为 `a.js` 对应的 Module 对象// isMain: 除入口文件为 `true` 外,其他模块都为 `false`Module._load = function(request, parent, isMain) {  let relResolveCacheIdentifier;  if (parent) {    debug('Module._load REQUEST %s parent: %s', request, parent.id);    // relativeResolveCache 是模块路径缓存,    // 用于加速父模块所在目录下的所有模块请求当前模块时    // 可以直接查询到实际路径,而不需要通过 _resolveFilename 查找文件    relResolveCacheIdentifier = `${parent.path}x00${request}`;    const filename = relativeResolveCache[relResolveCacheIdentifier];    if (filename !== undefined) {      const cachedModule = Module._cache[filename];      if (cachedModule !== undefined) {        updateChildren(parent, cachedModule, true);        if (!cachedModule.loaded)          return getExportsForCircularRequire(cachedModule);        return cachedModule.exports;      }      delete relativeResolveCache[relResolveCacheIdentifier];    }  }// 尝试查找模块文件路径,找不到模块抛出异常  const filename = Module._resolveFilename(request, parent, isMain);  // 如果是内置模块,从 `NativeModule` 加载  if (StringPrototypeStartsWith(filename, 'node:')) {    // Slice 'node:' prefix    const id = StringPrototypeSlice(filename, 5);    const module = loadNativeModule(id, request);    if (!module?.canBeRequiredByUsers) {      throw new ERR_UNKNOWN_BUILTIN_MODULE(filename);    }    return module.exports;  }// 如果缓存中已存在,将当前模块 push 到父模块的 children 字段  const cachedModule = Module._cache[filename];  if (cachedModule !== undefined) {    updateChildren(parent, cachedModule, true);    // 处理循环引用    if (!cachedModule.loaded) {      const parseCachedModule = cjsParseCache.get(cachedModule);      if (!parseCachedModule || parseCachedModule.loaded)        return getExportsForCircularRequire(cachedModule);      parseCachedModule.loaded = true;    } else {      return cachedModule.exports;    }  }// 尝试从内置模块加载  const mod = loadNativeModule(filename, request);  if (mod?.canBeRequiredByUsers) return mod.exports;  // Don't call updateChildren(), Module constructor already does.  const module = cachedModule || new Module(filename, parent);  if (isMain) {    process.mainModule = module;    module.id = '.';  }// 将 module 对象加入缓存  Module._cache[filename] = module;  if (parent !== undefined) {    relativeResolveCache[relResolveCacheIdentifier] = filename;  }  // 尝试加载模块,如果加载失败则删除缓存中的 module 对象,  // 同时删除父模块的 children 内的 module 对象。  let threw = true;  try {    module.load(filename);    threw = false;  } finally {    if (threw) {      delete Module._cache[filename];      if (parent !== undefined) {        delete relativeResolveCache[relResolveCacheIdentifier];        const children = parent?.children;        if (ArrayIsArray(children)) {          const index = ArrayPrototypeIndexOf(children, module);          if (index !== -1) {            ArrayPrototypeSplice(children, index, 1);          }        }      }    } else if (module.exports &&               !isProxy(module.exports) &&               ObjectGetPrototypeOf(module.exports) ===                 CircularRequirePrototypeWarningProxy) {      ObjectSetPrototypeOf(module.exports, ObjectPrototype);    }  }// 返回 exports 对象  return module.exports;};

module 对象上的 [load](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L963) 函数用于执行一个模块的加载:

Module.prototype.load = function(filename) {  debug('load %j for module %j', filename, this.id);  assert(!this.loaded);  this.filename = filename;  this.paths = Module._nodeModulePaths(path.dirname(filename));  const extension = findLongestRegisteredExtension(filename);  // allow .mjs to be overridden  if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs'])    throw new ERR_REQUIRE_ESM(filename, true);  Module._extensions[extension](this, filename);  this.loaded = true;  const esmLoader = asyncESM.esmLoader;  // Create module entry at load time to snapshot exports correctly  const exports = this.exports;  // Preemptively cache  if ((module?.module === undefined ||       module.module.getStatus() < kEvaluated) &&      !esmLoader.cjsCache.has(this))    esmLoader.cjsCache.set(this, exports);};

实际的加载动作是在 Module._extensions[extension](this, filename); 中进行的,根据扩展名的不同,会有不同的加载策略:

.js:调用 fs.readFileSync 读取文件内容,将文件内容包在 wrapper 中,需要注意的是,这里的 requireModule.prototype.require 而非内置模块的 require 方法。

const wrapper = [  '(function (exports, require, module, __filename, __dirname) { ',  'n});',];

.json:调用 fs.readFileSync 读取文件内容,并转换为对象。.node:调用 dlopen 打开 node 扩展。

Module.prototype.require 函数也是调用了静态方法 Module._load实现模块加载的:

Module.prototype.require = function(id) {  validateString(id, 'id');  if (id === '') {    throw new ERR_INVALID_ARG_VALUE('id', id,                                    'must be a non-empty string');  }  requireDepth++;  try {    return Module._load(id, this, /* isMain */ false);  } finally {    requireDepth--;  }};

总结

看到这里,cjs 模块的加载过程已经基本清晰了:

初始化 node,加载 NativeModule,用于加载所有的内置的 js 和 c++ 模块

运行内置模块 run_main

run_main 中引入用户模块系统 module

通过 module_load 方法加载入口文件,在加载时通过传入 module.requiremodule.exports 等让入口文件可以正常 require 其他依赖模块并递归让整个依赖树被完整加载。

在清楚了 cjs 模块加载的完整流程之后,我们还可以顺着这条链路阅读其他代码,比如 global 变量的初始化,esModule 的管理方式等,更深入地理解 node 内的各种实现。

更多node相关知识,请访问:nodejs 教程!

以上就是探索 Node.js 源码,详解cjs 模块的加载过程的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/834994.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月27日 09:50:04
下一篇 2025年11月27日 10:01:54

相关推荐

  • Uniapp 中如何不拉伸不裁剪地展示图片?

    灵活展示图片:如何不拉伸不裁剪 在界面设计中,常常需要以原尺寸展示用户上传的图片。本文将介绍一种在 uniapp 框架中实现该功能的简单方法。 对于不同尺寸的图片,可以采用以下处理方式: 极端宽高比:撑满屏幕宽度或高度,再等比缩放居中。非极端宽高比:居中显示,若能撑满则撑满。 然而,如果需要不拉伸不…

    2025年12月24日
    400
  • 如何让小说网站控制台显示乱码,同时网页内容正常显示?

    如何在不影响用户界面的情况下实现控制台乱码? 当在小说网站上下载小说时,大家可能会遇到一个问题:网站上的文本在网页内正常显示,但是在控制台中却是乱码。如何实现此类操作,从而在不影响用户界面(UI)的情况下保持控制台乱码呢? 答案在于使用自定义字体。网站可以通过在服务器端配置自定义字体,并通过在客户端…

    2025年12月24日
    800
  • 如何在地图上轻松创建气泡信息框?

    地图上气泡信息框的巧妙生成 地图上气泡信息框是一种常用的交互功能,它简便易用,能够为用户提供额外信息。本文将探讨如何借助地图库的功能轻松创建这一功能。 利用地图库的原生功能 大多数地图库,如高德地图,都提供了现成的信息窗体和右键菜单功能。这些功能可以通过以下途径实现: 高德地图 JS API 参考文…

    2025年12月24日
    400
  • 如何使用 scroll-behavior 属性实现元素scrollLeft变化时的平滑动画?

    如何实现元素scrollleft变化时的平滑动画效果? 在许多网页应用中,滚动容器的水平滚动条(scrollleft)需要频繁使用。为了让滚动动作更加自然,你希望给scrollleft的变化添加动画效果。 解决方案:scroll-behavior 属性 要实现scrollleft变化时的平滑动画效果…

    2025年12月24日
    000
  • 如何为滚动元素添加平滑过渡,使滚动条滑动时更自然流畅?

    给滚动元素平滑过渡 如何在滚动条属性(scrollleft)发生改变时为元素添加平滑的过渡效果? 解决方案:scroll-behavior 属性 为滚动容器设置 scroll-behavior 属性可以实现平滑滚动。 html 代码: click the button to slide right!…

    2025年12月24日
    500
  • 如何选择元素个数不固定的指定类名子元素?

    灵活选择元素个数不固定的指定类名子元素 在网页布局中,有时需要选择特定类名的子元素,但这些元素的数量并不固定。例如,下面这段 html 代码中,activebar 和 item 元素的数量均不固定: *n *n 如果需要选择第一个 item元素,可以使用 css 选择器 :nth-child()。该…

    2025年12月24日
    200
  • 使用 SVG 如何实现自定义宽度、间距和半径的虚线边框?

    使用 svg 实现自定义虚线边框 如何实现一个具有自定义宽度、间距和半径的虚线边框是一个常见的前端开发问题。传统的解决方案通常涉及使用 border-image 引入切片图片,但是这种方法存在引入外部资源、性能低下的缺点。 为了避免上述问题,可以使用 svg(可缩放矢量图形)来创建纯代码实现。一种方…

    2025年12月24日
    100
  • 如何让“元素跟随文本高度,而不是撑高父容器?

    如何让 元素跟随文本高度,而不是撑高父容器 在页面布局中,经常遇到父容器高度被子元素撑开的问题。在图例所示的案例中,父容器被较高的图片撑开,而文本的高度没有被考虑。本问答将提供纯css解决方案,让图片跟随文本高度,确保父容器的高度不会被图片影响。 解决方法 为了解决这个问题,需要将图片从文档流中脱离…

    2025年12月24日
    000
  • 为什么 CSS mask 属性未请求指定图片?

    解决 css mask 属性未请求图片的问题 在使用 css mask 属性时,指定了图片地址,但网络面板显示未请求获取该图片,这可能是由于浏览器兼容性问题造成的。 问题 如下代码所示: 立即学习“前端免费学习笔记(深入)”; icon [data-icon=”cloud”] { –icon-cl…

    2025年12月24日
    200
  • 如何利用 CSS 选中激活标签并影响相邻元素的样式?

    如何利用 css 选中激活标签并影响相邻元素? 为了实现激活标签影响相邻元素的样式需求,可以通过 :has 选择器来实现。以下是如何具体操作: 对于激活标签相邻后的元素,可以在 css 中使用以下代码进行设置: li:has(+li.active) { border-radius: 0 0 10px…

    2025年12月24日
    100
  • 如何模拟Windows 10 设置界面中的鼠标悬浮放大效果?

    win10设置界面的鼠标移动显示周边的样式(探照灯效果)的实现方式 在windows设置界面的鼠标悬浮效果中,光标周围会显示一个放大区域。在前端开发中,可以通过多种方式实现类似的效果。 使用css 使用css的transform和box-shadow属性。通过将transform: scale(1.…

    2025年12月24日
    200
  • 为什么我的 Safari 自定义样式表在百度页面上失效了?

    为什么在 Safari 中自定义样式表未能正常工作? 在 Safari 的偏好设置中设置自定义样式表后,您对其进行测试却发现效果不同。在您自己的网页中,样式有效,而在百度页面中却失效。 造成这种情况的原因是,第一个访问的项目使用了文件协议,可以访问本地目录中的图片文件。而第二个访问的百度使用了 ht…

    2025年12月24日
    000
  • 如何用前端实现 Windows 10 设置界面的鼠标移动探照灯效果?

    如何在前端实现 Windows 10 设置界面中的鼠标移动探照灯效果 想要在前端开发中实现 Windows 10 设置界面中类似的鼠标移动探照灯效果,可以通过以下途径: CSS 解决方案 DEMO 1: Windows 10 网格悬停效果:https://codepen.io/tr4553r7/pe…

    2025年12月24日
    000
  • 使用CSS mask属性指定图片URL时,为什么浏览器无法加载图片?

    css mask属性未能加载图片的解决方法 使用css mask属性指定图片url时,如示例中所示: mask: url(“https://api.iconify.design/mdi:apple-icloud.svg”) center / contain no-repeat; 但是,在网络面板中却…

    2025年12月24日
    000
  • 如何用CSS Paint API为网页元素添加时尚的斑马线边框?

    为元素添加时尚的斑马线边框 在网页设计中,有时我们需要添加时尚的边框来提升元素的视觉效果。其中,斑马线边框是一种既醒目又别致的设计元素。 实现斜向斑马线边框 要实现斜向斑马线间隔圆环,我们可以使用css paint api。该api提供了强大的功能,可以让我们在元素上绘制复杂的图形。 立即学习“前端…

    2025年12月24日
    000
  • 图片如何不撑高父容器?

    如何让图片不撑高父容器? 当父容器包含不同高度的子元素时,父容器的高度通常会被最高元素撑开。如果你希望父容器的高度由文本内容撑开,避免图片对其产生影响,可以通过以下 css 解决方法: 绝对定位元素: .child-image { position: absolute; top: 0; left: …

    2025年12月24日
    000
  • CSS 帮助

    我正在尝试将文本附加到棕色框的左侧。我不能。我不知道代码有什么问题。请帮助我。 css .hero { position: relative; bottom: 80px; display: flex; justify-content: left; align-items: start; color:…

    2025年12月24日 好文分享
    200
  • 前端代码辅助工具:如何选择最可靠的AI工具?

    前端代码辅助工具:可靠性探讨 对于前端工程师来说,在HTML、CSS和JavaScript开发中借助AI工具是司空见惯的事情。然而,并非所有工具都能提供同等的可靠性。 个性化需求 关于哪个AI工具最可靠,这个问题没有一刀切的答案。每个人的使用习惯和项目需求各不相同。以下是一些影响选择的重要因素: 立…

    2025年12月24日
    000
  • 如何用 CSS Paint API 实现倾斜的斑马线间隔圆环?

    实现斑马线边框样式:探究 css paint api 本文将探究如何使用 css paint api 实现倾斜的斑马线间隔圆环。 问题: 给定一个有多个圆圈组成的斑马线图案,如何使用 css 实现倾斜的斑马线间隔圆环? 答案: 立即学习“前端免费学习笔记(深入)”; 使用 css paint api…

    2025年12月24日
    000
  • 如何使用CSS Paint API实现倾斜斑马线间隔圆环边框?

    css实现斑马线边框样式 想定制一个带有倾斜斑马线间隔圆环的边框?现在使用css paint api,定制任何样式都轻而易举。 css paint api 这是一个新的css特性,允许开发人员创建自定义形状和图案,其中包括斑马线样式。 立即学习“前端免费学习笔记(深入)”; 实现倾斜斑马线间隔圆环 …

    2025年12月24日
    100

发表回复

登录后才能评论
关注微信