Webpack离线插件如何向sw.js添加资产

时间:2016-09-07 11:24:01

标签: javascript webpack offline-caching webpack-plugin

我尝试将webpack和offline-plugin添加到现有项目中使用gulp - webpack工作得很好,但添加offline-plugin会给你带来困难,

我所做的是添加offline-plugin throw npm

webpack.confing.js

const {resolve} = require('path')
const webpackValidator = require('webpack-validator')
const OfflinePlugin = require('offline-plugin');

 module.exports = webpackValidator({
            context: resolve('app/scripts'),
            entry: ["./main.js","./skrollr.js"],
            output: {
                filename: "[name].[hash].js",
            },devtool: 'eval',
            module: {
                loaders :[
                        {test:/\.(jsx|js)$/,exclude: /node_modules/,loader: 'imports?jQuery=jquery,$=jquery,this=>window'},
                        { test: /\.css$/,exclude: /node_modules/, loader: "style-loader!css-loader" },
                        { test: /\.eot$/, loader: "file-loader" },
                        { test: /\.woff2$/, loader: "file-loader" },
                        { test: /\.woff$/, loader: "file-loader" },
                        { test: /\.svg$/, loader: "file-loader" },
                        { test: /\.ttf$/, loader: "file-loader" }]
                    },
            resolve: {
                        extensions: ['', '.js', '.jsx','.css','.eot','.woff2','.woff','.svg','.ttf']
                    },

                plugins: [new OfflinePlugin({
                    caches:{"main":['images/bgz.jpg','app/images/hamburger.svg','app/images/logo_grey.svg']},
                    externals:['images/bgz.jpg','app/images/hamburger.svg','app/images/logo_grey.svg'],ServiceWorker:{output:'/sw.js'}})]
});

main.js是项目的主要文件

var skrollr = require('./skrollr.js');
require('../styles/main.css');

 (function () {
   'use strict';
    $("#skrollr-body").css("background","green");

     require('../../node_modules/offline-plugin/runtime').install();
     if ('serviceWorker' in navigator) {
         navigator.serviceWorker.register('/sw.js', {scope:           './'}).then(function(registration) {

     document.querySelector('#status').textContent = 'succeeded';


        }).catch(function(error) {

          document.querySelector('#status').textContent = error;
       });
         } else {
           // The current browser doesn't support service workers.
              var aElement = document.createElement('a');
                aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
            aElement.textContent = 'unavailable';
             document.querySelector('#status').appendChild(aElement);
          }

现在,当我运行该项目时,我使用:

node_modules/.bin/webpack

它返回

hash: 496a6f3a79110e844236
Version: webpack 1.13.2
Time: 3167ms
                   Asset       Size  Chunks             Chunk Names
main.496a6f3a79110e844236.js    1.01 MB       0  [emitted]  main
                   sw.js    14.4 kB          [emitted]  
appcache/manifest.appcache  134 bytes          [emitted]  
appcache/manifest.html   58 bytes          [emitted]  
 [0] multi main 40 bytes {0} [built]
  + 8 hidden modules
  Child __offline_serviceworker:
    + 3 hidden modules

然后我运行gulp服务器:

gulp serve

我检查sw.js返回并显示只有bundle.js提供的文件不是我添加到插件主要cahches对象的任何文件:

var __wpo = {
"assets": {
 "main": [
   "../.././scripts/bundle.js"
   ],
  "additional": [],
   "optional": []
 },
"hashesMap": {
 "f250efd8234ae0d9bbb5e1db4a4ce8bf": "../.././scripts/bundle.js"
 },
 "strategy": "all",
 "version": "9/6/2016, 6:40:24 PM",
 "name": "webpack-offline",
 "relativePaths": true
 };

我使用离线插件的方式是当前的,以及如何添加其他文件以进行缓存并从服务工作者那里获得,我应该添加什么样的内容来实现它将webpack confing autmatclicy

我的项目文件树:

/_
  /app
      /index.html
      /images
          /bgz.jpg
          /hamburger.svg
          /logo_grey.svg
      /fonts
      /scripts
         /main.js
         /bundel.js 

  /node_moudles
  sw.js
  packge.json
  webpack.config.js 

1 个答案:

答案 0 :(得分:0)

我用过这个:

new OfflinePlugin({
  version: '[hash]',
  responseStrategy: 'network-first',
  safeToUseOptionalCaches: true,
  ServiceWorker: {
    events: true,
    output: 'static/js/sw.js'
  }
})

似乎包含了所有资产。