【问题标题】:webpack configuration using html-webpack-plugin使用 html-webpack-plugin 配置 webpack
【发布时间】:2018-03-19 00:08:45
【问题描述】:

我正在使用带有构建设置的 HTML-Webpack-plugin:

build: {
  env: require('./prod.env'),
  index: path.resolve(__dirname, '../app/templates/dist/index.html'),
  assetsRoot: path.resolve(__dirname, '../app/static'),
  assetsSubDirectory: 'dist'

应用结构:

app-
    static-
        dist-
            css- minified css files
            js- minified js files
    templates-
        dist-
            index.html

使用 npm run build 构建输出时,输出 index.html 文件如下所示:

<!DOCTYPE html><html><head><meta charset=utf-8><title>app</title><link href=/dist/css/app.22f236.css

但是,对于 index.html 中的所有路径,我希望 href 路径在 /dist 之前包含 /static,即

/static/dist/css...  

我的 webpack.prod.conf.js:

var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vender modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

我有什么方法可以更改 index.html 中的注入路径以在每个路径前面包含一个父文件夹? (除了编写一个 bash 脚本来执行此操作)。

【问题讨论】:

  • 你的 webpack 配置看起来怎么样?
  • 我已将整个 prod.conf 文件设置添加到上述问题
  • 尝试在 webpack 中添加publicPath: '/' output。这有帮助吗?

标签: javascript webpack


【解决方案1】:

编译资产的输出路径不依赖于您可以通过html-webpack-plugin 提供的设置(HTML 文件本身除外)。您必须配置编译器输出路径和模块规则,以确保资产在所需的公共路径上发出。

【讨论】:

  • 资产在 assetsRoot: path.resolve(__dirname, '../app/static') 处发出正常,但我希望 webpack 为 index.html 中的路径添加目录名称前缀以便服务器可以找到资产,如果可能的话
  • 您必须为此获取模块规则。例如,如果您想更改引用 CSS 资源的路径并使用 extract-text-webpack-plugin,则必须将其配置为 publicPathoption。 html-webpack-plugin 仅使用资产的公共路径,因为它在添加到编译时在其他地方定义。使用file-loader 等添加的资产也是如此。
猜你喜欢
  • 2020-10-07
  • 2019-12-18
  • 2016-11-16
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 2016-01-16
  • 2017-07-11
相关资源
最近更新 更多