2016-07-13 107 views
5

sto cercando di sostituire una variabile in index.html che assomiglia a questo:usare l'HTML-webpack-plugin con stringa-sostituzione-loader in webpack

<meta name='author' content=$variable>

nel file di configurazione che uso:

{ 
    test: /index\.html$/, 
    loader: 'string-replace', 
    query: { 
     search: '$variable', 
     replace: 'stuff to inject', 
    }, 
    } 

nell'array loaders, e poi in plugins:

new HtmlWebpackPlugin({ 
    template: conf.path.src('src/index.html'), 
    inject: true, 
}) 
risultati

Ma questa impostazione in:

ERROR in ./~/html-webpack-plugin/lib/loader.js!./src/index.html Module parse failed (...) Unexpected token (1:0) You may need an appropriate loader to handle this file type.

Avete qualche idea che cosa questo può essere causato da o come posso mettere a punto questo?

+0

Per il debug sto utilizzando [iron-node] (https://github.com/sa/iron-node) che consente di aggiungere istruzioni debugger ai moduli nodo – jantimon

risposta

5

È causato da string-replace-plugin che si aspetta un modulo che esporta una stringa. Dovresti convertire il file HTML nel modulo CommonJS.

Ad esempio, questo è il modo utilizzando raw-loader:

prima, aggiungere citazioni attribuire contenuti in HTML

<meta name='author' content='$variable'>` 

e

{ 
    test: /index\.html$/, 
    loader: 'string-replace?search=$variable&replace=stuff to inject!raw' 
    } 
+0

Bello - pensi che potremmo migliorare l'html- webpack-plugin in qualche modo per migliorare il messaggio di errore? – jantimon

+0

Grazie! Ho anche lavorato su questo utilizzando il loader HTML – wap300

1

risposta di Konstantin funziona bene ed è buono se vuoi sostituire un valore. Volevo sostituire i valori multipli in modo aggiunto il seguente al mio loaders gamma

{ 
    test: /\.html$/, 
    loader: 'raw' 
    }, 
    { 
    test: /\.html$/, 
    loader: 'string-replace', 
    query: { 
     multiple: [ 
     {search: '$variable1', replace: 'replacement 1'}, 
     {search: '$variable2', replace: 'replacement 2'} 
     ] 
    } 
    } 

Il cambiamento chiave è quello di eseguire prima il file html attraverso il raw caricatore, e quindi è possibile utilizzare tutte le config normale per il string-replace-loader.

+1

Questo ha funzionato nel webpack 1.X ma penso che non funzioni con webpack 2 e 3. – SharpCoder