Rails 如何从 JS 文件中引用已编译的 Webpack 包文件的路径?
How to reference the path to a compiled Webpack pack file from inside a JS file in Rails?
我正在为 Rails 6 RC2 应用程序使用 webpacker
gem(版本 4.0.7),我也在使用 serviceworker-rails
中间件 gem(版本 0.6.0)将 Service Worker 与 Rails 集成。
现在,我想创建一个 serviceworker.js
包文件(我从 serviceworker-rails
README 文件复制并修改了它)以便它可以由 Webpack 提供服务并被路由使用 serviceworker-rails
中间件。
所以,在 app/javascript/packs/serviceworker.js.erb
(安装了 erb-loader
)中,我这样做了:
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
'<%= asset_pack_path "application.js" %>',
'<%= asset_pack_path "application.css" %>',
'/offline.html',
]);
})
);
}
...
这样做会导致 Webpack 无法编译 Service Worker 包,因为我不能在包文件中使用 asset_pack_path
(甚至在编译之前无法获取已编译包的路径)。所以问题是,如何在我的 Service Worker 脚本中引用编译后的 JS 和 CSS pack 的路径,以便 Service Worker 可以缓存这些文件?
所以,在深入挖掘了这么久之后,我在 GitHub 上找到了这个 issue 的解决方案(并且还意识到我没有正确阅读和理解错误,因为错误是undefined method 'asset_pack_path'
并且与编译无关)。只需执行以下操作即可解决问题:
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
<% helpers = ActionController::Base.helpers %>
'<%= helpers.asset_pack_path "application.js" %>',
'<%= helpers.asset_pack_path "application.css" %>',
'/offline.html',
]);
})
);
}
...
我正在为 Rails 6 RC2 应用程序使用 webpacker
gem(版本 4.0.7),我也在使用 serviceworker-rails
中间件 gem(版本 0.6.0)将 Service Worker 与 Rails 集成。
现在,我想创建一个 serviceworker.js
包文件(我从 serviceworker-rails
README 文件复制并修改了它)以便它可以由 Webpack 提供服务并被路由使用 serviceworker-rails
中间件。
所以,在 app/javascript/packs/serviceworker.js.erb
(安装了 erb-loader
)中,我这样做了:
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
'<%= asset_pack_path "application.js" %>',
'<%= asset_pack_path "application.css" %>',
'/offline.html',
]);
})
);
}
...
这样做会导致 Webpack 无法编译 Service Worker 包,因为我不能在包文件中使用 asset_pack_path
(甚至在编译之前无法获取已编译包的路径)。所以问题是,如何在我的 Service Worker 脚本中引用编译后的 JS 和 CSS pack 的路径,以便 Service Worker 可以缓存这些文件?
所以,在深入挖掘了这么久之后,我在 GitHub 上找到了这个 issue 的解决方案(并且还意识到我没有正确阅读和理解错误,因为错误是undefined method 'asset_pack_path'
并且与编译无关)。只需执行以下操作即可解决问题:
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
<% helpers = ActionController::Base.helpers %>
'<%= helpers.asset_pack_path "application.js" %>',
'<%= helpers.asset_pack_path "application.css" %>',
'/offline.html',
]);
})
);
}
...