【问题标题】:Link css filename with hash to index.html after the Extract Text Plugin在提取文本插件之后将带有哈希的 css 文件名链接到 index.html
【发布时间】:2017-02-27 02:03:30
【问题描述】:

我想问一下,在为我的生产运行 npm 之后,如何将生成的带有哈希名称的 css 文件链接到我的 index.html:

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

这是我的 webpack 配置中的插件,它将生成带有哈希的文件名,因为每次我为生产构建它都会生成一个新的哈希文件名。有没有办法不用手动编辑index.html就可以自动完成?

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

【问题讨论】:

    标签: webpack extract-text-plugin


    【解决方案1】:

    上面@Jonik提到的在运行时由服务器(Node.js)生成html的可能解决方案。

    用于开发:

    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;
    

    用于生产:

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

    然后:

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

    'style' 变量将包含由 ExtractTextPlugin 捆绑的 CSS。

    【讨论】:

      【解决方案2】:

      html-webpack-plugin 就是答案。

      对于生成的css和js文件,它可以自动将linkscript标签添加到index.html

      【讨论】:

      • 服务器在运行时生成html不是答案。
      • @Jonik 那么答案是什么? ;)
      • @Jonik,根据您的提及发布了答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 2017-12-13
      • 2019-07-28
      • 2013-01-18
      相关资源
      最近更新 更多