我正在与"next": "^9.3.2"一起工作,并集成了一名服务工作者(包括这一点,以防其他人有类似的问题):
档案结构:
pages
public
static
serviceWorker.js
server
index.js在server/index.js中
async function start() {
const dev = process.env.NODE_ENV !== 'production';
const app = nextJS({ dev });
const server = express();
....
server.get('/serviceWorker.js', (req, res) => {
res.sendFile(path.resolve(__dirname, '../public', 'serviceWorker.js'));
});
/* later */
if (process.env.NODE_ENV === 'production') {
server.use(express.static('.next/static'));
server.get('/service-worker.js', (req, res) => {
res.sendFile(path.resolve(__dirname, 'public', 'serviceWorker.js'));
});在public/serviceWorker.js中
var currentCaches ={ css:'CSS',图像:‘图像’};
const cacheFiles = {
css: [
// 'http://localhost:8016/semantic-ui-css/semantic.min.css',
// 'http://localhost:8016/font-awesome/css/font-awesome.min.css',
// 'http://localhost:8016/leaflet/dist/leaflet.css',
// 'http://localhost:8016/esri-leaflet-geocoder/dist/esri-leaflet-geocoder.css',
// 'http://localhost:8016/styles/styles.css',
// 'http://localhost:8016/leaflet-routing-machine/dist/leaflet-routing-machine.css'
],
images: [
// 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
// 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
// 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
// 'http://localhost:8016/public/static/media/search@2x.png',
// 'http://localhost:8016/public/static/uploads/profile-avatars/placeholder.jpg'
]
};
self.addEventListener('install', function(event) {
console.log('Hello world from the Service Worker ');
event.waitUntil(
Promise.all([
caches.open(currentCaches.css).then(cache => {
return cache.addAll(cacheFiles.css);
}),
caches.open(currentCaches.images).then(cache => {
return cache.addAll(cacheFiles.images);
})
])
);
});现在,我在上面的对象中声明css路径*就像在我的_app.js文件中那样:
import 'semantic-ui-css/semantic.min.css';
import 'font-awesome/css/font-awesome.min.css';
import 'leaflet/dist/leaflet.css';
import 'esri-leaflet-geocoder/dist/esri-leaflet-geocoder.css';
import '../styles/styles.scss';
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css';因此,我的问题是,既然next.js在生产构建中释放出一个static/css:
.next
cache
server
static
chunks
css < -----
476a94f2.d9a9e468.chunk.css
dbd51271.19268786.chunk.css
styles.9ca4e15c.chunk.css如何让serviceWorker知道这些文件名(以及图像、字体、svg等)?因为我假设这些数字将有助于缓存!
谢谢!
发布于 2020-12-04 16:30:09
一般来说,如果您想获得一个哈希URL列表,以便在您的服务工作人员中使用,您需要一些方法来集成您的web应用程序的构建过程。
考虑到您使用的是Next.js,像next-offline这样的插件可以帮助您做两件事:
将URLs.
workbox-precaching确保正确缓存URL并保持其最新。如果您不喜欢使用next-offline,您可以自己实现类似的东西,但是您需要使用类似于next-assets-manifest的东西来获取散列URL的列表,编写您自己的服务工作者,并研究如何将这些URL注入到服务工作人员中。
https://stackoverflow.com/questions/65147044
复制相似问题