Как мне кешировать импортированные модули в es6?
Модули ES6 позволяют нам создать единую точку входа следующим образом:
foo.js будет храниться в кеше браузера. Это желательно, пока я не отправлю новую версию foo.js в рабочую среду.
Обычной практикой является добавление параметра строки запроса с уникальным идентификатором, чтобы заставить браузер получать новую версию файла js ( foo.js? Cb = 1234 ).
Как этого можно достичь с помощью шаблона модуля es6?
12 ответов
Просто подумайте, но вы должны иметь возможность заставить Webpack помещать хеш содержимого во все разделенные пакеты и записывать этот хеш в ваши операторы импорта за вас. Я считаю, что по умолчанию работает второй вариант.
Что я сделал, так это обработал очистку кеша на веб-сервере (nginx в моем случае)
Вместо того, чтобы служить
Подавайте это так, где 123456 — ваш ключ очистки кеша
И укажите местоположение в nginx, например
При запросе scripts/123456/main.js будут предоставлены scripts/main.min.js и обновление key приведет к обслуживанию нового файла, это решение хорошо работает и для cdns.
Если вы используете Visual Studio 2022 и TypeScript для написания кода, вы можете следовать соглашению о добавлении номера версии к именам файлов сценариев, например. MyScript.v1.ts . Когда вы вносите изменения и переименовываете файл в MyScript.v2.ts , Visual Studio показывает следующее диалоговое окно, похожее на следующее:
Если вы нажмете Yes , он продолжит и обновит все файлы, которые импортировали этот модуль, чтобы ссылаться на MyScript.v2.ts вместо MyScript.v1.ts . Браузер также заметит изменение имени и загрузит новые модули, как и ожидалось.
Это не идеальное решение (например, если вы переименуете часто используемый модуль, в конечном итоге может обновиться множество файлов), но оно простое!
С моей точки зрения решением здесь может быть динамический импорт .
Шаг 1) Создайте файл манифеста с помощью gulp или webpack. Вот такое отображение:
Шаг 2) Создайте файловую функцию для разрешения ваших путей
Шаг 3) Используйте динамический импорт
Я пробую его в Chrome, и он работает. Обработка относительных путей здесь — непростая задача.
Вы можете использовать ETags, как указано в предыдущем ответе, или, альтернативно, использовать Last-Modified по отношению к If-Modified-Since .
Вот возможный сценарий:
- Браузер сначала загружает ресурс. Сервер отвечает Last-Modified: Sat, 28 Mar 2020 18:12:45 GMT и Cache-Control: max-age=60 .
- Если второй раз запрос инициируется раньше, чем через 60 секунд после первого, браузер обслуживает файл из кеша и не делает фактический запрос к серверу.
- Если запрос инициируется через 60 секунд, браузер сочтет кешированный файл устаревшим и отправит запрос с заголовком If-Modified-Since: Sat, 28 Mar 2020 18:12:45 GMT . Сервер проверит это значение и:
- Если файл был изменен после указанной даты, он выдаст ответ 200 с новым файлом в теле.
- Если файл был не изменен после указанной даты, сервер выдаст статус 304 «не изменен» с пустым телом.
Я закончил с этой настройкой для сервера Apache:
Вы можете установить max-age по своему вкусу.
Мы должны отключить ETag. В противном случае Apache будет отвечать 200 OK каждый раз (это ошибка). Кроме того, он вам не понадобится, если вы будете использовать кеширование по дате модификации.
Для всего этого есть одно решение, не использующее строку запроса. скажем, файлы вашего модуля находятся в /modules/ . Используйте относительное разрешение модуля ./ или ../ при импорте модулей, а затем перепишите свои пути на стороне сервера, чтобы включить номер версии. Используйте что-то вроде /modules/x.x.x/ , затем перепишите путь на /modules/ . Теперь вы можете просто иметь глобальный номер версии для модулей, включив свой первый модуль с <script type=»module» src=»https://question-it.com/modules/1.1.2/foo.mjs»></script>
Или, если вы не можете переписать пути, просто поместите файлы в папку /modules/version/ во время разработки и переименуйте папку version в номер версии и обновите путь в теге скрипта при публикации.
Эта работа для меня
Решение, которое пришло мне в голову, но я не буду использовать, потому что мне это не нравится. LOL — это
Использование «метода» импорта позволяет передать строку литерала шаблона. Я также добавил его в окно, чтобы он был легко доступен независимо от того, насколько глубоко я импортирую файлы js. Причина, по которой мне это не нравится, заключается в том, что я должен использовать «await», что означает, что он должен быть заключен в метод async.
Для меня работает относительный путь:
ИЗМЕНИТЬ
Поскольку этот ответ отклонен, я обновляю его. Модуль не всегда перезагружается. В первый раз вам нужно перезагрузить модуль вручную, и тогда браузер (по крайней мере, Chrome) «поймет», что файл изменен, и затем перезагружает файл каждый раз, когда он обновляется.
Заголовки HTTP спешат на помощь. Обслуживайте свои файлы с помощью ETag, который является контрольной суммой файл. S3 делает это, например, по умолчанию. При повторной попытке импортировать файл браузер запросит файл, на этот раз прикрепив ETag к «if-none-match»: сервер проверит, соответствует ли ETag текущему файлу, и отправит обратно либо 304 Not Modified, сохраняя полосу пропускания и время, или новое содержимое файла (с его новым ETag).
Таким образом, если вы измените один файл в своем проекте, пользователю не придется загружать все содержимое всех остальных модулей. Было бы разумно добавить также короткий заголовок max-age , чтобы, если один и тот же модуль будет запрошен дважды за короткое время, не будет дополнительных запросов.
Если вы добавите очистку кеша (например, добавив? X =
В обоих сценариях вы все равно собираетесь делать запрос для каждого файла (импортированные файлы в каскаде будут создавать новые запросы, которые, по крайней мере, могут заканчиваться маленькими 304, если вы используете etags). Чтобы избежать этого, вы можете использовать динамический импорт e.g if (userClickedOnSomethingAndINeedToLoadSomeMoreStuff) < import('./someModule').then('. ') >
Я создал плагин Babel, который добавляет хэш содержимого для каждого имени модуля (статический и динамический импорт).
Затем вы можете использовать Cache-control: immutable , чтобы позволить UA (браузерам, прокси и т. д.) кэшировать эти версионные URL-адреса на неопределенный срок. Некоторые max-age , вероятно, более разумны, в зависимости от вашей настройки.
Вы можете использовать необработанные исходные файлы во время разработки (и тестирования), а затем преобразовывать и минимизировать файлы для производства.
Я пришел к выводу, что очистка кеша не должна использоваться с модулем ES.
На самом деле, если у вас есть версия в URL-адресе, версия действует как очистка кеша. Например, https://unpkg.com/react@18.2. 0/umd/react.production.min.js
Если у вас нет версии в URL-адресе, используйте следующий HTTP-заголовок Cache-Control: max-age=0, no-cache , чтобы браузер всегда проверял наличие новой версии файла.
no-cache указывает браузеру кэшировать файл, но всегда выполнять проверку
no-store указывает браузеру не кэшировать файл. Не используйте его!
Другой подход: перенаправление
unpkg.com решил эту проблему с помощью перенаправления HTTP. Поэтому это не идеальное решение, потому что оно включает 2 HTTP-запроса вместо 1.
Первый запрос — перенаправить на последнюю версию файла (не кэшированную или кэшированную в течение короткого периода времени).
Второй запрос — получить файл JS (кэшированный)
=> Все файлы JS включают версии в URL (и имеют агрессивную стратегию кэширования).
=> Удаление версии в URL-адресе приведет к перенаправлению HTTP 302, указывающему на последнюю версию файла.
Убедитесь, что перенаправление не кэшируется браузером или кэшируется в течение короткого периода времени. (unpkg позволяет кэшировать 600 секунд, но это зависит от вас)
О множественных HTTP-запросах: Да, если вы импортируете 100 модулей, ваш браузер выполнит 100 запросов. Но с HTTP2/HTTP3 это уже не проблема, потому что все запросы будут мультиплексированы в 1 (для вас это прозрачно)
О рекурсии: Если модуль, который вы импортируете, также импортирует другие модули, вам следует проверить <link rel=»modulepreload»> (источник блог разработчиков Chrome).
Спецификация modulepreload на самом деле позволяет опционально загружать не только запрошенный модуль, но и все его дерево зависимостей. Браузеры не обязаны этого делать, но могут.
Если вы используете эту технику в производстве, мне очень интересно получить ваши отзывы!
Caching
Модули кэшируются после первой загрузки. Это означает (среди прочего), что каждый вызов require(‘foo’) будет возвращать один и тот же объект, если он будет разрешен в один и тот же файл.
При условии, что require.cache не изменен, несколько вызовов require(‘foo’) не приведут к многократному выполнению кода модуля. Это важная особенность. С его помощью можно возвращать «частично выполненные» объекты, что позволяет загружать транзитивные зависимости, даже если они вызывают циклы.
Чтобы модуль выполнял код несколько раз,экспортируйте функцию и вызывайте ее.
Предостережения по кэшированию модулей
Модули кэшируются в зависимости от их разрешенного имени файла. Поскольку модули могут преобразовываться в другое имя файла в зависимости от местоположения вызывающего модуля (загрузка из папок node_modules ), это не гарантия, что require(‘foo’) всегда будет возвращать один и тот же объект, если он будет разрешаться в разные файлы ,
Кроме того, в файловых системах или операционных системах, нечувствительных к регистру, разные разрешенные имена файлов могут указывать на один и тот же файл, но кеш по-прежнему будет обрабатывать их как разные модули и перезагружать файл несколько раз. Например, require(‘./foo’) и require(‘./FOO’) возвращают два разных объекта, независимо от того, являются ли ./foo и ./FOO одним и тем же файлом.
Core modules
Добавлен node: поддержка импорта для require(. ) .
Node.js имеет несколько модулей,скомпилированных в бинарный файл.Более подробно эти модули описаны в других разделах данной документации.
Основные модули определены в исходном коде Node.js и находятся в папке lib/ .
Основные модули можно идентифицировать с помощью префикса node: , и в этом случае он обходит require кеш. Например, require(‘node:http’) всегда будет возвращать встроенный модуль HTTP, даже если есть запись require.cache с таким именем.
Некоторые основные модули всегда предпочтительно загружаются, если их идентификатор передается в require() . Например, require(‘http’) всегда будет возвращать встроенный модуль HTTP, даже если есть файл с таким именем. Список основных модулей, которые можно загрузить без использования префикса node: , представлен как module.builtinModules .
Cycles
Когда есть циклические вызовы require() , модуль может не завершить выполнение, когда он возвращается.
Рассмотрим эту ситуацию:
Когда main.js нагрузки a.js , то a.js в свою очередь , загружает b.js . В тот момент, b.js пытается загрузить a.js . Для того , чтобы предотвратить зацикливание, незавершенная копия из a.js объекта экспорта возвращается в b.js модуль. b.js завершает загрузку, и его объект exports предоставляется модулю a.js .
К тому времени, как main.js загрузит оба модуля, они оба будут готовы . Таким образом, результат этой программы будет:
Для корректной работы циклических модульных зависимостей внутри приложения требуется тщательное планирование.
File modules
Если точное имя файла не найдено, Node.js попытается загрузить требуемое имя файла с добавленными расширениями: .js , .json и, наконец , .node . При загрузке файла с другим расширением (например , .cjs ) его полное имя должно быть передано в require() , включая расширение файла (например require(‘./file.cjs’) ).
.json анализируются как текстовые файлы JSON, файлы .node интерпретируются как скомпилированные дополнительные модули, загружаемые с помощью process.dlopen() . Файлы с любым другим расширением (или вообще без расширения) анализируются как текстовые файлы JavaScript. Обратитесь к разделу « Определение модульной системы », чтобы понять, какая цель синтаксического анализа будет использоваться.
Обязательный модуль с префиксом ‘/’ — это абсолютный путь к файлу. Например, require(‘/home/marco/foo.js’) загрузит файл по адресу /home/marco/foo.js .
Требуемый модуль с префиксом ‘./’ относится к файлу, вызывающему require() . То есть circle.js должен находиться в том же каталоге, что и foo.js , чтобы require(‘./circle’) его нашел.
Без node_modules ‘/’ , ‘./’ или ‘../’ для обозначения файла модуль должен быть либо основным модулем, либо загружаться из папки node_modules .
Если заданный путь не существует, require() выдаст ошибку MODULE_NOT_FOUND .
Папки как модули
Есть три способа, которыми папка может быть передана в require() в качестве аргумента.
Первый — создать файл package.json в корне папки, в котором указан main модуль. Пример файла package.json может выглядеть следующим образом:
Если бы это было в папке в ./some-library , тогда require(‘./some-library’) попытался бы загрузить ./some-library/lib/some-library.js .
Если в каталоге нет файла package.json или если «main» запись отсутствует или не может быть разрешена, то Node.js попытается загрузить файл index.js или index.node из этого каталога. Например, если в предыдущем примере не было файла package.json require(‘./some-library’) попытается загрузить:
- ./some-library/index.js
- ./some-library/index.node
Если эти попытки не увенчаются успехом,то Node.js сообщит об отсутствии всего модуля с ошибкой по умолчанию:
Во всех трех вышеприведенных случаях вызов import(‘./some-library’) приведет к ошибке ERR_UNSUPPORTED_DIR_IMPORT . Использование экспорта подпутей пакетов или импорта подпутей может обеспечить те же преимущества организации сдерживания, что и папки в качестве модулей, и работает как для require , так и import .
Загрузка из папок node_modules
Если идентификатор модуля, переданный в require() , не является основным модулем и не начинается с ‘/’ , ‘../’ или ‘./’ , тогда Node.js запускается в каталоге текущего модуля и добавляет /node_modules и пытается загрузить модуль из этого места. Node.js не будет добавлять node_modules к пути, который уже заканчивается на node_modules .
Если его там нет,то он перемещается в родительский каталог,и так далее,пока не будет достигнут корень файловой системы.
Например, если файл в ‘/home/ry/projects/foo.js’ называется require(‘bar.js’) , то Node.js будет искать в следующих местах в таком порядке:
- /home/ry/projects/node_modules/bar.js
- /home/ry/node_modules/bar.js
- /home/node_modules/bar.js
- /node_modules/bar.js
Это позволяет программам локализовать свои зависимости,чтобы они не вступали в конфликт.
Можно потребовать определенные файлы или подмодули, распространяемые вместе с модулем, путем включения суффикса пути после имени модуля. Например, require(‘example-module/path/to/file’) разрешит path/to/file относительно того, где находится example-module . Путь с суффиксом следует той же семантике разрешения модуля.
Загрузка из глобальных папок
Если для переменной среды NODE_PATH задан список абсолютных путей, разделенных двоеточиями, то Node.js будет искать по этим путям модули, если они не найдены где-либо еще.
В Windows NODE_PATH разделяется точкой с запятой ( ; ) вместо двоеточия.
NODE_PATH изначально был создан для поддержки загрузки модулей с разных путей до того, как был определен текущий алгоритм разрешения модулей .
NODE_PATH по-прежнему поддерживается, но теперь он менее необходим, поскольку экосистема Node.js выработала соглашение о размещении зависимых модулей. Иногда развертывания, основанные на NODE_PATH , демонстрируют удивительное поведение, когда люди не знают, что нужно установить NODE_PATH . Иногда зависимости модуля меняются, в результате чего при NODE_PATH загружается другая версия (или даже другой модуль) .
Кроме того,Node.js будет искать в следующем списке GLOBAL_FOLDERS:
- 1: $HOME/.node_modules
- 2: $HOME/.node_libraries
- 3: $PREFIX/lib/node
Где $HOME — это домашний каталог пользователя, а $PREFIX — это настроенный Node.js node_prefix .
В основном по историческим причинам.
Настоятельно рекомендуется размещать зависимости в локальной папке node_modules . Они будут загружаться быстрее и надежнее.
Как кэшировать js библиотеку при импорте
CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the ECMAScript modules standard used by browsers and other JavaScript runtimes.
In Node.js, each file is treated as a separate module. For example, consider a file named foo.js :
On the first line, foo.js loads the module circle.js that is in the same directory as foo.js .
Here are the contents of circle.js :
The module circle.js has exported the functions area() and circumference() . Functions and objects are added to the root of a module by specifying additional properties on the special exports object.
Variables local to the module will be private, because the module is wrapped in a function by Node.js (see module wrapper). In this example, the variable PI is private to circle.js .
The module.exports property can be assigned a new value (such as a function or object).
Below, bar.js makes use of the square module, which exports a Square class:
The square module is defined in square.js :
The CommonJS module system is implemented in the module core module.
Enabling #
Node.js has two module systems: CommonJS modules and ECMAScript modules.
By default, Node.js will treat the following as CommonJS modules:
Files with a .cjs extension;
Files with a .js extension when the nearest parent package.json file contains a top-level field «type» with a value of «commonjs» .
Files with a .js extension when the nearest parent package.json file doesn’t contain a top-level field «type» . Package authors should include the «type» field, even in packages where all sources are CommonJS. Being explicit about the type of the package will make things easier for build tools and loaders to determine how the files in the package should be interpreted.
Files with an extension that is not .mjs , .cjs , .json , .node , or .js (when the nearest parent package.json file contains a top-level field «type» with a value of «module» , those files will be recognized as CommonJS modules only if they are being included via require() , not when used as the command-line entry point of the program).
Calling require() always use the CommonJS module loader. Calling import() always use the ECMAScript module loader.
Accessing the main module #
When a file is run directly from Node.js, require.main is set to its module . That means that it is possible to determine whether a file has been run directly by testing require.main === module .
For a file foo.js , this will be true if run via node foo.js , but false if run by require(‘./foo’) .
When the entry point is not a CommonJS module, require.main is undefined , and the main module is out of reach.
Package manager tips #
The semantics of the Node.js require() function were designed to be general enough to support reasonable directory structures. Package manager programs such as dpkg , rpm , and npm will hopefully find it possible to build native packages from Node.js modules without modification.
Below we give a suggested directory structure that could work:
Let’s say that we wanted to have the folder at /usr/lib/node/<some-package>/<some-version> hold the contents of a specific version of a package.
Packages can depend on one another. In order to install package foo , it may be necessary to install a specific version of package bar . The bar package may itself have dependencies, and in some cases, these may even collide or form cyclic dependencies.
Because Node.js looks up the realpath of any modules it loads (that is, it resolves symlinks) and then looks for their dependencies in node_modules folders, this situation can be resolved with the following architecture:
- /usr/lib/node/foo/1.2.3/ : Contents of the foo package, version 1.2.3.
- /usr/lib/node/bar/4.3.2/ : Contents of the bar package that foo depends on.
- /usr/lib/node/foo/1.2.3/node_modules/bar : Symbolic link to /usr/lib/node/bar/4.3.2/ .
- /usr/lib/node/bar/4.3.2/node_modules/* : Symbolic links to the packages that bar depends on.
Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use.
When the code in the foo package does require(‘bar’) , it will get the version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar . Then, when the code in the bar package calls require(‘quux’) , it’ll get the version that is symlinked into /usr/lib/node/bar/4.3.2/node_modules/quux .
Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in /usr/lib/node , we could put them in /usr/lib/node_modules/<name>/<version> . Then Node.js will not bother looking for missing dependencies in /usr/node_modules or /node_modules .
In order to make modules available to the Node.js REPL, it might be useful to also add the /usr/lib/node_modules folder to the $NODE_PATH environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to require() , the packages themselves can be anywhere.
The .mjs extension #
Due to the synchronous nature of require() , it is not possible to use it to load ECMAScript module files. Attempting to do so will throw a ERR_REQUIRE_ESM error. Use import() instead.
The .mjs extension is reserved for ECMAScript Modules which cannot be loaded via require() . See Determining module system section for more info regarding which files are parsed as ECMAScript modules.
All together #
To get the exact filename that will be loaded when require() is called, use the require.resolve() function.
Putting together all of the above, here is the high-level algorithm in pseudocode of what require() does:
Caching #
Modules are cached after the first time they are loaded. This means (among other things) that every call to require(‘foo’) will get exactly the same object returned, if it would resolve to the same file.
Provided require.cache is not modified, multiple calls to require(‘foo’) will not cause the module code to be executed multiple times. This is an important feature. With it, «partially done» objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.
To have a module execute code multiple times, export a function, and call that function.
Module caching caveats #
Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require(‘foo’) will always return the exact same object, if it would resolve to different files.
Additionally, on case-insensitive file systems or operating systems, different resolved filenames can point to the same file, but the cache will still treat them as different modules and will reload the file multiple times. For example, require(‘./foo’) and require(‘./FOO’) return two different objects, irrespective of whether or not ./foo and ./FOO are the same file.
Core modules #
Added node: import support to require(. ) .
Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation.
The core modules are defined within the Node.js source and are located in the lib/ folder.
Core modules can be identified using the node: prefix, in which case it bypasses the require cache. For instance, require(‘node:http’) will always return the built in HTTP module, even if there is require.cache entry by that name.
Some core modules are always preferentially loaded if their identifier is passed to require() . For instance, require(‘http’) will always return the built-in HTTP module, even if there is a file by that name. The list of core modules that can be loaded without using the node: prefix is exposed as module.builtinModules .
Cycles #
When there are circular require() calls, a module might not have finished executing when it is returned.
Consider this situation:
When main.js loads a.js , then a.js in turn loads b.js . At that point, b.js tries to load a.js . In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.
By the time main.js has loaded both modules, they’re both finished. The output of this program would thus be:
Careful planning is required to allow cyclic module dependencies to work correctly within an application.
File modules #
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js , .json , and finally .node . When loading a file that has a different extension (e.g. .cjs ), its full name must be passed to require() , including its file extension (e.g. require(‘./file.cjs’) ).
.json files are parsed as JSON text files, .node files are interpreted as compiled addon modules loaded with process.dlopen() . Files using any other extension (or no extension at all) are parsed as JavaScript text files. Refer to the Determining module system section to understand what parse goal will be used.
A required module prefixed with ‘/’ is an absolute path to the file. For example, require(‘/home/marco/foo.js’) will load the file at /home/marco/foo.js .
A required module prefixed with ‘./’ is relative to the file calling require() . That is, circle.js must be in the same directory as foo.js for require(‘./circle’) to find it.
Without a leading ‘/’ , ‘./’ , or ‘../’ to indicate a file, the module must either be a core module or is loaded from a node_modules folder.
If the given path does not exist, require() will throw a MODULE_NOT_FOUND error.
Folders as modules #
There are three ways in which a folder may be passed to require() as an argument.
The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:
If this was in a folder at ./some-library , then require(‘./some-library’) would attempt to load ./some-library/lib/some-library.js .
If there is no package.json file present in the directory, or if the «main» entry is missing or cannot be resolved, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the previous example, then require(‘./some-library’) would attempt to load:
- ./some-library/index.js
- ./some-library/index.node
If these attempts fail, then Node.js will report the entire module as missing with the default error:
In all three above cases, an import(‘./some-library’) call would result in a ERR_UNSUPPORTED_DIR_IMPORT error. Using package subpath exports or subpath imports can provide the same containment organization benefits as folders as modules, and work for both require and import .
Loading from node_modules folders #
If the module identifier passed to require() is not a core module, and does not begin with ‘/’ , ‘../’ , or ‘./’ , then Node.js starts at the directory of the current module, and adds /node_modules , and attempts to load the module from that location. Node.js will not append node_modules to a path already ending in node_modules .
If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.
For example, if the file at ‘/home/ry/projects/foo.js’ called require(‘bar.js’) , then Node.js would look in the following locations, in this order:
- /home/ry/projects/node_modules/bar.js
- /home/ry/node_modules/bar.js
- /home/node_modules/bar.js
- /node_modules/bar.js
This allows programs to localize their dependencies, so that they do not clash.
It is possible to require specific files or sub modules distributed with a module by including a path suffix after the module name. For instance require(‘example-module/path/to/file’) would resolve path/to/file relative to where example-module is located. The suffixed path follows the same module resolution semantics.
Loading from the global folders #
If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then Node.js will search those paths for modules if they are not found elsewhere.
On Windows, NODE_PATH is delimited by semicolons ( ; ) instead of colons.
NODE_PATH was originally created to support loading modules from varying paths before the current module resolution algorithm was defined.
NODE_PATH is still supported, but is less necessary now that the Node.js ecosystem has settled on a convention for locating dependent modules. Sometimes deployments that rely on NODE_PATH show surprising behavior when people are unaware that NODE_PATH must be set. Sometimes a module’s dependencies change, causing a different version (or even a different module) to be loaded as the NODE_PATH is searched.
Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:
- 1: $HOME/.node_modules
- 2: $HOME/.node_libraries
- 3: $PREFIX/lib/node
Where $HOME is the user’s home directory, and $PREFIX is the Node.js configured node_prefix .
These are mostly for historic reasons.
It is strongly encouraged to place dependencies in the local node_modules folder. These will be loaded faster, and more reliably.
The module wrapper #
Before a module’s code is executed, Node.js will wrap it with a function wrapper that looks like the following:
- It keeps top-level variables (defined with var , const , or let ) scoped to the module rather than the global object.
- It helps to provide some global-looking variables that are actually specific to the module, such as:
- The module and exports objects that the implementor can use to export values from the module.
- The convenience variables __filename and __dirname , containing the module’s absolute filename and directory path.
The module scope #
__dirname #
The directory name of the current module. This is the same as the path.dirname() of the __filename .
Example: running node example.js from /Users/mjr
__filename #
The file name of the current module. This is the current module file’s absolute path with symlinks resolved.
For a main program this is not necessarily the same as the file name used in the command line.
See __dirname for the directory name of the current module.
Running node example.js from /Users/mjr
Given two modules: a and b , where b is a dependency of a and there is a directory structure of:
- /Users/mjr/app/a.js
- /Users/mjr/app/node_modules/b/b.js
References to __filename within b.js will return /Users/mjr/app/node_modules/b/b.js while references to __filename within a.js will return /Users/mjr/app/a.js .
exports #
A reference to the module.exports that is shorter to type. See the section about the exports shortcut for details on when to use exports and when to use module.exports .
module #
A reference to the current module, see the section about the module object. In particular, module.exports is used for defining what a module exports and makes available through require() .
require(id) #
- id <string> module name or path
- Returns: <any> exported module content
Used to import modules, JSON , and local files. Modules can be imported from node_modules . Local modules and JSON files can be imported using a relative path (e.g. ./ , ./foo , ./bar/baz , ../foo ) that will be resolved against the directory named by __dirname (if defined) or the current working directory. The relative paths of POSIX style are resolved in an OS independent fashion, meaning that the examples above will work on Windows in the same way they would on Unix systems.
require.cache #
Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module. This does not apply to native addons, for which reloading will result in an error.
Adding or replacing entries is also possible. This cache is checked before built-in modules and if a name matching a built-in module is added to the cache, only node: -prefixed require calls are going to receive the built-in module. Use with care!
require.extensions #
Instruct require on how to handle certain file extensions.
Process files with the extension .sjs as .js :
Deprecated. In the past, this list has been used to load non-JavaScript modules into Node.js by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node.js program, or compiling them to JavaScript ahead of time.
Avoid using require.extensions . Use could cause subtle bugs and resolving the extensions gets slower with each registered extension.
require.main #
The Module object representing the entry script loaded when the Node.js process launched, or undefined if the entry point of the program is not a CommonJS module. See «Accessing the main module».
In entry.js script:
require.resolve(request[, options]) #
The paths option is now supported.
- request <string> The module path to resolve.
- options <Object>
- paths <string[]> Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of GLOBAL_FOLDERS like $HOME/.node_modules , which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the node_modules hierarchy is checked from this location.
Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.
If the module can not be found, a MODULE_NOT_FOUND error is thrown.
require.resolve.paths(request) #
- request <string> The module path whose lookup paths are being retrieved.
- Returns: <string[]> | <null>
Returns an array containing the paths searched during resolution of request or null if the request string references a core module, for example http or fs .
The module object #
In each module, the module free variable is a reference to the object representing the current module. For convenience, module.exports is also accessible via the exports module-global. module is not actually a global but rather local to each module.
module.children #
The module objects required for the first time by this one.
module.exports #
The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to module.exports . Assigning the desired object to exports will simply rebind the local exports variable, which is probably not what is desired.
For example, suppose we were making a module called a.js :
Then in another file we could do:
Assignment to module.exports must be done immediately. It cannot be done in any callbacks. This does not work:
exports shortcut #
The exports variable is available within a module’s file-level scope, and is assigned the value of module.exports before the module is evaluated.
It allows a shortcut, so that module.exports.f = . can be written more succinctly as exports.f = . . However, be aware that like any variable, if a new value is assigned to exports , it is no longer bound to module.exports :
When the module.exports property is being completely replaced by a new object, it is common to also reassign exports :
To illustrate the behavior, imagine this hypothetical implementation of require() , which is quite similar to what is actually done by require() :
module.filename #
The fully resolved filename of the module.
module.id #
The identifier for the module. Typically this is the fully resolved filename.
module.isPreloading #
- Type: <boolean> true if the module is running during the Node.js preload phase.
module.loaded #
Whether or not the module is done loading, or is in the process of loading.
Как кэшировать js библиотеку при импорте
Модули в JavaScript

CommonJS
Работа с модулями в Node.js

Дополнительные свойства у module и require
- построение графа зависимостей;
- оценка расположения модулей и загрузка файлов;
- анализ модулей;
- запись информации о модулях и создание полей всех экспортируемых значений (без их состояний);
- выполнение сценария модулей для получение состояний;
- запись состояний экспортируемых частей модулей.
- referencingScriptOrModule — идентификатор текущего модуля, откуда происходит импорт;
- specifier — идентификатор импортируемого модуля, в данном случае ./modulePath .
How to handle caching of JavaScript files imported as ES6 module
Previously, I used the following method to force the browser to reload my JavaScript file if there was a new version available.
My HTML is automatically generated (e.g. with PHP), so this is easy to automate.
New situation
Now I want to use ES6 modules and import my common code. My HTML becomes:
And app.js contains the import:
Problem
Now my question: how do I influence the caching of common.js in the new scenario?
I don’t want to manually edit app.js every time I edit common.js . I also don’t want to dynamically generate/pre-process any of my JavaScript files, if possible.
2 Answers 2
Just use Webpack, and you can keep doing your trick because all the javascript will be in a single file.
You said you don’t want to pre-process your javascript files. I would reconsider that stance. Most modern web applications (and their associated frameworks like React, Angular, Vue.js) are built using some sort of preprocessor/packager that bundles all the javascript for the app into one or more files.
There are many good reasons to do this that we don’t need to re-iterate in full here, but briefly, you can do type-checking (e.g. TypeScript), linting, tree-shaking, optimization, obfuscation, and compacting easily.
Bundled javascript is often smaller (by a large margin), faster, and more correct. It leads to shorter loading times and less bandwidth usage, which is particularly important when so many more than 50% of web traffic is from mobile these days.
While it might be a bit of learning curve, it’s the direction our industry is going, and with good reason. The reason there isn’t an easy way to include a cache-busting query parameter in ES module important is probably because the designers of the language considered it an anti-pattern.
How do I cache bust imported modules in es6?
ES6 modules allows us to create a single point of entry like so:
foo.js will be stored in the browser cache. This is desirable until I push a new version of foo.js to production.
It is common practice to add a query string param with a unique id to force the browser to fetch a new version of a js file (foo.js?cb=1234)
How can this be achieved using the es6 module pattern?
12 Answers 12
There is one solution for all of this that doesn’t involve query string. let’s say your module files are in /modules/ . Use relative module resolution ./ or ../ when importing modules and then rewrite your paths in server side to include version number. Use something like /modules/x.x.x/ then rewrite path to /modules/ . Now you can just have global version number for modules by including your first module with <script type=»module» src=»https://stackoverflow.com/modules/1.1.2/foo.mjs»></script>
Or if you can’t rewrite paths, then just put files into folder /modules/version/ during development and rename version folder to version number and update path in script tag when you publish.

HTTP headers to the rescue. Serve your files with an ETag that is the checksum of the file. S3 does that by default at example. When you try to import the file again, the browser will request the file, this time attaching the ETag to a «if-none-match» header: the server will verify if the ETag matches the current file and send back either a 304 Not Modified, saving bandwith and time, or the new content of the file (with its new ETag).
This way if you change a single file in your project the user will not have to download the full content of every other module. It would be wise to add a short max-age header too, so that if the same module is requested twice in a short time there won’t be additional requests.
If you add cache busting (e.g. appending ?x= through a bundler, or adding the checksum to every file name) you will force the user to download the full content of every necessary file at every new project version.
In both scenario you are going to do a request for each file anyway (the imported files on cascade will produce new requests, which at least may end in small 304 if you use etags). To avoid that you can use dynamic imports e.g if (userClickedOnSomethingAndINeedToLoadSomeMoreStuff)
импорт библиотеки javascript один раз
Я создаю веб-сайт, который импортирует библиотеку javascript (находится внутри <head> ):
что значит,
при каждой загрузке страницы (независимо от того, какая страница на моем сайте) эта строка существует.Я хотел знать, загружают ли современные браузеры библиотеку один раз, а затем кешируют ее,
или при каждой загрузке страницы — библиотека javascript повторно загружается.2 ответы
При нормальных обстоятельствах большинство браузеров будут кэшировать файл javascript, если он неоднократно запрашивается с одного и того же URL-адреса; однако мое определение нормальные обстоятельства заключается в том, как обычно настраиваются серверы. Реальный результат зависит от того, что заголовки кеша сервер отправляет, а также изменяется ли URL-адрес (что не ясно из вашего вопроса).
В StackOverflow много вопросов о кэшировании JavaScript. Этот включает в себя что-то вроде сборника.
ответ дан 23 мая ’17, 13:05
Я использую игровой фреймворк (веб-фреймворк на основе Java). Мне нужно выяснить, могу ли я контролировать заголовки кеша (думаю, что это возможно) — носок
How do I cache bust imported modules in es6?
ES6 modules allows us to create a single point of entry like so:
foo.js will be stored in the browser cache. This is desirable until I push a new version of foo.js to production.
It is common practice to add a query string param with a unique id to force the browser to fetch a new version of a js file (foo.js?cb=1234)
How can this be achieved using the es6 module pattern?
13 Answers 13
There is one solution for all of this that doesn’t involve query string. let’s say your module files are in /modules/ . Use relative module resolution ./ or ../ when importing modules and then rewrite your paths in server side to include version number. Use something like /modules/x.x.x/ then rewrite path to /modules/ . Now you can just have global version number for modules by including your first module with <script type=»module» src=»https://stackoverflow.com/modules/1.1.2/foo.mjs»></script>
Or if you can’t rewrite paths, then just put files into folder /modules/version/ during development and rename version folder to version number and update path in script tag when you publish.

HTTP headers to the rescue. Serve your files with an ETag that is the checksum of the file. S3 does that by default at example. When you try to import the file again, the browser will request the file, this time attaching the ETag to a «if-none-match» header: the server will verify if the ETag matches the current file and send back either a 304 Not Modified, saving bandwith and time, or the new content of the file (with its new ETag).
This way if you change a single file in your project the user will not have to download the full content of every other module. It would be wise to add a short max-age header too, so that if the same module is requested twice in a short time there won’t be additional requests.
If you add cache busting (e.g. appending ?x= through a bundler, or adding the checksum to every file name) you will force the user to download the full content of every necessary file at every new project version.
In both scenario you are going to do a request for each file anyway (the imported files on cascade will produce new requests, which at least may end in small 304 if you use etags). To avoid that you can use dynamic imports e.g if (userClickedOnSomethingAndINeedToLoadSomeMoreStuff)
Как кэшировать js библиотеку при импорте





How do I cache bust imported modules in es6?
ES6 modules allows us to create a single point of entry like so:
foo.js will be stored in the browser cache. This is desirable until I push a new version of foo.js to production.
It is common practice to add a query string param with a unique id to force the browser to fetch a new version of a js file (foo.js?cb=1234)
How can this be achieved using the es6 module pattern?
11 Answers 11
There is one solution for all of this that doesn’t involve query string. let’s say your module files are in /modules/ . Use relative module resolution ./ or ../ when importing modules and then rewrite your paths in server side to include version number. Use something like /modules/x.x.x/ then rewrite path to /modules/ . Now you can just have global version number for modules by including your first module with <script type=»module» src=»https://stackoverflow.com/modules/1.1.2/foo.mjs»></script>
Or if you can’t rewrite paths, then just put files into folder /modules/version/ during development and rename version folder to version number and update path in script tag when you publish.

HTTP headers to the rescue. Serve your files with an ETag that is the checksum of the file. S3 does that by default at example. When you try to import the file again, the browser will request the file, this time attaching the ETag to a «if-none-match» header: the server will verify if the ETag matches the current file and send back either a 304 Not Modified, saving bandwith and time, or the new content of the file (with its new ETag).
This way if you change a single file in your project the user will not have to download the full content of every other module. It would be wise to add a short max-age header too, so that if the same module is requested twice in a short time there won’t be additional requests.
If you add cache busting (e.g. appending ?x= through a bundler, or adding the checksum to every file name) you will force the user to download the full content of every necessary file at every new project version.
In both scenario you are going to do a request for each file anyway (the imported files on cascade will produce new requests, which at least may end in small 304 if you use etags). To avoid that you can use dynamic imports e.g if (userClickedOnSomethingAndINeedToLoadSomeMoreStuff)