2014-07-03 16 views
15

mio punto di ingresso webpack include una [hash] nel nome:Includere il collegamento diretto ai punti di ingresso del pacchetto Web nell'applicazione HTML?

entry: "index.js", 
output: { 
    path: "build/", 
    filename: "index-[hash].js", 
} 

Come posso collegare direttamente a quel punto di ingresso da HTML della mia domanda?

Per esempio, mi piacerebbe il codice HTML che viene inviato al client per includere:

<script src="build/index-41d40fe7b20ba1dce81f.js"></script> 

Come posso fare questo? Esiste un plugin che può generare un manifest di entry point che la mia applicazione può leggere ed emettere i nomi di file appropriati?

risposta

25

Il html-webpack-plugin (Sono l'autore) genererà un index.html per fare riferimento al nomefile del pacchetto hash corretto.

var HtmlWebpackPlugin = require("html-webpack-plugin"); 
var webpackConfig = { 
    entry: "index.js", 
    output: { 
     path: "build/", 
     filename: "index-[hash].js", 
    }, 
    plugins: [new HtmlWebpackPlugin()] 
} 

Questo produrrà build/index.html che include il tuo pacco con un tag <script>.

+1

Impressionante plug-in. – Max

+0

Ehi, davvero, fantastico plug-in. C'è un'opzione per usarlo senza creare un nuovo file ".html" e senza usare un "modello blueimp"? Ho un file html esistente che voglio aggiornare –

+1

Non sono sicuro che questa fosse un'opzione in aprile quando hai commentato l'ultima volta, ma sembra che 6 mesi dopo, ci siano le opzioni 'template' (ottiene un modello esistente per il nome del file) e 'templateContent' (aggiungi direttamente una stringa di HTML). Sono d'accordo, comunque, fantastico plugin. – trysis

8

Ho appena iniziato a giocare con il webpack e ho trovato che gulp è adatto per scrivere i file js appena hash su index.html. Se preferisci non usare il gulp, this discussion regarding doing something similar with a plugin potrebbe aiutare un po '. Ecco un frammento gulpfile che potrebbe aiutare un po 'così:

var util = require('util'); 
var path = require('path'); 
var gulp = require('gulp'); 
var runSequence = require('run-sequence'); 
var rimraf = require('rimraf'); 
var gzip = require('gulp-gzip'); 
var notify = require('gulp-notify'); 
var gutil = require('gulp-util'); 
var webpack = require('webpack'); 
var webpackConfig = require('./client/webpack.config'); 
var through2 = require('through2'); 

gulp.task("webpack", function (cb) { 
    webpack(webpackConfig, function (err, stats) { 
     if (err) throw new gutil.PluginError("webpack", err); 

     var jsFilename = stats.toJson().assetsByChunkName['app']; 
     console.log('>>>>', jsFilename); 
     // if source-maps are turned on, you'll get [ 'somefile.js', 'somefile.js.map' ] 
     if (util.isArray(jsFilename)) { 
      jsFilename = jsFilename.filter(function (filename) { 
       return path.extname(filename).toLowerCase() === '.js' 
      }).shift(); 
     } 

     // write the hashed main.js to /dist/index.html 
     gulp.src('./client/index.html') 
      .on('error', handleErrors) 
      .pipe(through2.obj(function (vinylFile, enc, tCb) { 
       vinylFile.contents = new Buffer(String(vinylFile.contents) 
        .replace('main.js', jsFilename)); 
       this.push(vinylFile); 
       tCb(); 
      })) 
      .pipe(gulp.dest('./dist/')); 

     cb(); 
    }); 
}); 

function handleErrors() { 
    var args = Array.prototype.slice.call(arguments); 
    notify.onError({ title: 'Error', message: '<%= error.message %>'}).apply(this, args); 
    this.emit('end'); 
} 

gulp.task('gzip-deploy', function() { 
    return gulp.src('./dist/**/*') 
     .on('error', handleErrors) 
     .pipe(gzip()) 
     .pipe(gulp.dest('./dist/')); 
}); 

gulp.task('clean', function (cb) { 
    return rimraf('./dist', cb); 
}); 

gulp.task('default', function (cb) { 
    runSequence('clean', 'webpack', cb); 
}); 

gulp.task('deploy', function (cb) { 
    webpackConfig.plugins = webpackConfig.plugins = [ 
     new webpack.optimize.UglifyJsPlugin(), 
     new webpack.DefinePlugin({ 
      "process.env": { 
       NODE_ENV: JSON.stringify("production") 
      } 
     }) 
    ]; 
    webpackConfig.watch = false; 
    webpackConfig.devtool = null; 
    webpackConfig.output.filename = "main-[hash].js"; 

    runSequence('clean', 'webpack', 'gzip-deploy', cb); 
}); 

Ecco il mio file webpack.config.js così per un po' di contesto:

var path = require('path'); 

module.exports = { 
    context: __dirname, 
    devtool: 'source-map', 
    entry: { 
     app: './main.js' 
    }, 
    watch: true, 
    output: { 
     path: path.join(__dirname, "/../dist"), 
     filename: "main.js" 
    }, 
    module: { 
     loaders: [ 
      { test: /\.js$/, loader: 'jsx-loader?harmony' }, 
      { test: /\.css$/, loader: "style-loader!css-loader" }, 
      { test: /\.less$/, loader: "style-loader!css-loader!less-loader" }, 
      { test: /\.png$/, loader: "url-loader?prefix=img/&limit=8192" }, 
      { test: /\.jpg$/, loader: "url-loader?prefix=img/&limit=8192" }, 
      { test: /\.gif$/, loader: "url-loader?prefix=img/&limit=8192" }, 
      { test: /\.woff$/, loader: "url-loader?prefix=font/&limit=8192" }, 
      { test: /\.eot$/, loader: "file-loader?prefix=font/" }, 
      { test: /\.ttf$/, loader: "file-loader?prefix=font/" }, 
      { test: /\.svg$/, loader: "file-loader?prefix=font/" } 
     ] 
    }, 
    resolve: { 
     extensions: ['', '.js', '.json'], 
     modulesDirectories: ['node_modules'] 
    }, 
    plugins: [] 
}; 
+3

C'è anche un 'stats.toJson(). AssetsByChunkName' che è un oggetto che mappa' chunkName' in nome/i dei file. –

+0

Grazie! Ciò semplifica notevolmente il compito di gulp ('stats.toJson(). Assets.reduce' si sentiva sporco). Codice modificato in base al tuo suggerimento. – Max

Problemi correlati