2

我想问一下,在为我的生产运行 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")
]
4

2 回答 2

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。

于 2018-04-17T12:18:35.007 回答
0

html-webpack-plugin就是答案。

它可以自动添加linkscript标记index.html生成的css和js文件。

于 2017-02-27T05:37:21.770 回答