2017-06-04 41 views
0

如何在我的HTML模板中替換指向當前塊散列的變量?構建期間如何獲得webpack塊散列?

我的HTML模板看起來是這樣的:

<html> 
    <head> 
     <link href="$css" rel="stylesheet"> 
    </head> 
    <body> 
     <h1>Hello World</h1> 
    </body> 
</html> 

我試圖把它打造這樣的:

<html> 
    <head> 
     <link href="app.c824da43.css" rel="stylesheet"> 
    </head> 
    <body> 
     <h1>Hello World</h1> 
    </body> 
</html> 

我嘗試使用字符串替換[name].[chunkhash:8].css,但呈現字面上:

<html> 
    <head> 
     <link href="[name].[chunkhash:8].css" rel="stylesheet"> 
    </head> 
    <body> 
     <h1>Hello World</h1> 
    </body> 
</html> 

我的項目:

. 
├── dist 
│   ├── app.c824da43.css 
│   └── index.html 
├── html 
│   └── index.html 
├── package.json 
├── sass 
│   └── main.scss 
└── webpack.config.js 

webpack.config.js

var webpack = require('webpack'); 
var outdir = __dirname + '/dist'; 
const ExtractTextPlugin = require("extract-text-webpack-plugin"); 

module.exports = { 
    entry: { 
     app: [ 
      './sass/main.scss', 
      './html/index.html', 
     ] 
    }, 
    output: { 
     path: outdir, 
     filename: '[name].[chunkhash:8].js' 
    }, 
    module: { 
     rules: [ 
      { 
       test: /\.s[ac]ss$/, 
       use: ExtractTextPlugin.extract({ 
        use: ['css-loader', 'sass-loader'] 
       }) 
      }, 
      { 
       test: /\.html$/, 
       use: [ 
        { 
         loader: "file-loader", 
         options: { 
          name: "/[name].[ext]", 
         }, 
        }, 
        { 
         loader: 'string-replace-loader', 
         query: { 
          search: /\$css/, 
       // What do I need to put here? 
          replace: '/[name].[chunkhash:8].css' 
         } 
        }, 
        { 
         loader: "extract-loader", 
        }, 
        { 
         loader: 'html-loader', 
         options: { 
          minimize: true, 
          removeComments: true, 
          collapseWhitespace: true 
         } 
        } 
       ] 
      } 
     ] 
    }, 
    plugins: [ 
     new ExtractTextPlugin("[name].[chunkhash:8].css"), 
    ] 
}; 

package.json

{ 
    "devDependencies": { 
    "css-loader": "^0.28.4", 
    "extract-loader": "^0.1.0", 
    "extract-text-webpack-plugin": "^2.1.0", 
    "file-loader": "^0.11.1", 
    "html-loader": "^0.4.5", 
    "node-sass": "^4.5.3", 
    "sass-loader": "^6.0.5", 
    "string-replace-loader": "^1.2.0", 
    "webpack": "^2.6.1" 
    } 
} 

Demo with solution

+0

也許這會幫助:https://github.com/webpack/webpack/tree/master/examples/multiple-commons-chunks –

回答

1

從您的配置的WebPack的index.html切入點。使用HtmlWebpackPlugin複製您的index.html。該插件會自動將CSS <link>標籤添加到您生成的html中。

https://github.com/jantimon/html-webpack-plugin

如果使用插件,所有minifications應插件,而不是HTML裝載機在裏面你/\.html$/規則來執行。

new HtmlWebpackPlugin({ 
    template: 'html/index.html', 
    filename: 'index.html', 
    minify: { 
    collapseWhitespace: true, 
    removeComments: true 
    } 
})