We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
项目运行,依赖 node_modules,但是为什么删除还可以继续运行呢?
因为 Node 的 require 是有缓存策略的。
Node 对于引入过的模块会进行缓存,来减少二次引入的开销。浏览器只缓存文件,Node 是缓存编译和执行后的对象。
以. .. 和 / 开始的标识符,都会被当作文件模块来处理。
在分析路径的时候,require 方法会把路径转换成真实路径,并把它当成索引,把编译执行后的结果存放到缓存里,让下一次加载更快速。
在项目中,打印 require.cache 可以看见缓存的文件模块,如下图:
这些是 Node 缓存的,且 require 是 Node 的 api,所以在浏览器中打印 require.cache 会报 Uncaught ReferenceError: require is not defined 的错误。
当删除掉 node_modules 以后,只要我们依赖的模块的不需要执行,就可以继续运行。一旦我们需要利用某个包做一些处理,在没有 node_modules 的情况下,缓存就不起作用了。
例如当写 less 的时候,需要编译 less ,自然要用要到相关依赖,这时如果删除掉 node_modules,缓存的依赖也起不到编译 less 的作用,就会报错:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
项目运行,依赖 node_modules,但是为什么删除还可以继续运行呢?
因为 Node 的 require 是有缓存策略的。
Node 缓存
Node 对于引入过的模块会进行缓存,来减少二次引入的开销。浏览器只缓存文件,Node 是缓存编译和执行后的对象。
前端项目使用的路径形式的文件模块
以. .. 和 / 开始的标识符,都会被当作文件模块来处理。
在分析路径的时候,require 方法会把路径转换成真实路径,并把它当成索引,把编译执行后的结果存放到缓存里,让下一次加载更快速。
在项目中,打印 require.cache 可以看见缓存的文件模块,如下图:
这些是 Node 缓存的,且 require 是 Node 的 api,所以在浏览器中打印 require.cache 会报 Uncaught ReferenceError: require is not defined 的错误。
当删除掉 node_modules 以后,只要我们依赖的模块的不需要执行,就可以继续运行。一旦我们需要利用某个包做一些处理,在没有 node_modules 的情况下,缓存就不起作用了。
例如当写 less 的时候,需要编译 less ,自然要用要到相关依赖,这时如果删除掉 node_modules,缓存的依赖也起不到编译 less 的作用,就会报错:
参考:《深入浅出 Node.js》
The text was updated successfully, but these errors were encountered: