0

不确定我是否正确地处理了这个问题,但我正在尝试在 Webpack 中使用带有文件加载器的把手模板。我遇到的问题是我有图像的资产文件夹没有被复制到 dist 文件夹,并且正在使用文件加载器解决 img src 以提取图像。如果有一篇我找不到有用的帖子,请分享,或者如果有一篇包含有用信息的文章,我也会采纳。

提前感谢您的帮助。

Webpack.config

const webpack = require('webpack');

module.exports = {
  entry: "./src/index.js",
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        handlebarsLoader: {}
      }
    })
  ],
  module: {
    rules: [
      {
        test: /\.handlebars$/,
        loader: "handlebars-loader"
      },
      {
        test: /\.html$/,
        use: ["html-loader"]
      },
      {
        test: /\.(svg|png|jpe?g|gif)$/i,
        use: {
          loader: "file-loader",
          options: {
            name: "[name].[hash].[ext]",
            outputPath: "imgs/",
            useRelativePath: true
          }
        }
      }
    ]
  }
}

车把模板

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>{{ htmlWebpackPlugins.options.title }}</title>
</head>

<body>
  {{> templates/title}}
  <img src="./assets/serve.svg" alt="Serve svg" />
</body>

</html>

包.json

  "name": "Webpackolypse",
  "version": "1.0.0",
  "private": true,
  "description": "",
  "main": "./src/index.js",
  "scripts": {
    "start": "webpack-dev-server --config webpack.dev.js --open",
    "build": "webpack --config webpack.prod.js --verbose"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "copy-webpack-plugin": "^5.1.1",
    "css-loader": "^3.2.1",
    "file-loader": "^5.0.2",
    "handlebars-loader": "^1.7.1",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.9.0",
    "node-sass": "^4.13.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.1",
    "webpack-merge": "^4.2.2"
  },
  "dependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "handlebars": "^4.5.3",
    "sass": "^1.24.0"
  }
}
4

1 回答 1

3

您需要安装CopyWebpackPlugin才能将资产复制到 dist 文件夹。我在 webpack 4 中遇到了同样的问题。

尝试使用这个插件

const CopyWebpackPlugin = require('copy-webpack-plugin');

plugins: [

      new CopyWebpackPlugin([
                {
                    from: './src/assets',
                    to: './assets'
                }
            ])
]

于 2019-12-28T18:05:49.977 回答