Link css filename with hash to index.html after the Extract Text Plugin

孤街醉人 提交于 2019-12-11 03:08:20

问题


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.



来源:https://stackoverflow.com/questions/42476697/link-css-filename-with-hash-to-index-html-after-the-extract-text-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!