Link css filename with hash to index.html after th

2019-07-10 00:26发布

问题:

I would like to ask how can I link the generated css files with a hash name to my index.html after I run the npm for my production:

"build-production": "webpack -p --progress --colors --config webpack.config.production.js"

This is the plugin in my webpack config that will generate the filename with hash since every time I build for production it generates a new hash filename. Is there a way that can automatically do it without manually editting the index.html?

plugins: [
    new ExtractTextPlugin("css/[name][contenthash].css")
]

回答1:

html-webpack-plugin is the answer.

It can automatically add link and script tag to index.html for generated css and js file.



回答2:

A possible solution for the case of generating html by server (Node.js) in runtime, mentioned by @Jonik above.

For development:

const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('../../internals/webpack/webpack.dev.babel');

const compiler = webpack(webpackConfig);
const middleware = webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
  silent: true,
  stats: 'errors-only',
});

const fileSystem = middleware.fileSystem;
const encoding = 'utf-8';
const outputPath = compiler.outputPath;

For production:

const fs = require('fs');
const path= require('path');

const fileSystem = fs;
const encoding = { encoding: 'utf-8' };
const outputPath = path.resolve(process.cwd(), 'build');

And then:

let style = '';
fileSystem.readdirSync(outputPath).forEach((file) => {
  if (file.indexOf('.css') !== -1) {
    style += fileSystem.readFileSync(`${outputPath}/${file}`, encoding);
  }
});

The 'style' variable will contain your css bundled by ExtractTextPlugin.