webpack配置less以及js中引入的图片问题

1.问题重现

当我做了这个配置以后,发现less里的图片可以正常展现到页面,但是js里的图片以及其他文件都不能正常展现,都报404
原始配置如下:


// 如果有額外的.babelrc配置的話就可以使用這段代碼1
// module.exports = {
//   module: {
//     rules: [
//       {
//         test:/\.jsx?$/,
//         use: ['babel-loader'],
//         exclude:/node_modules/  //排除 node_modules目錄
//       }
//     ]
//   }
// }
// 如果有額外的.babelrc配置的話就可以使用這段代碼2
// 在webpack中配置 babel,如果沒有額外的.babelrc配置的話就可以使用這段代碼1
//webpack.config.js
// 首先引入插件1
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isDev = (process.env.NODE_ENV.trim()) === "development"; //html-webpack-plugin 的 config 的妙用4-1
const { CleanWebpackPlugin } = require('clean-webpack-plugin');//清理dist目錄的插件
const path = require('path');//設置出口使用
const config = require('./public/config')[isDev ? 'dev' : 'build'];//html-webpack-plugin 的 config 的妙用4-2
module.exports = {
  entry: './src/index.js', //webpack的默認配置,也可以寫一個數組
  output: {
    path: path.resolve(__dirname, 'dist'), //必須是絕對路徑
    // filename: 'bundle.js',
    // filename: 'bundle.[hash].js',
    filename: 'bundle.[hash:6].js',//考虑到CDN缓存的问题,我们一般会给文件名加上 hash
    // publicPath: '../' 打包上线之前要改一下这个哦
  },
  mode: isDev ? 'development' : 'production',//html-webpack-plugin 的 config 的妙用4-3
  module: {
      rules: [
          {
              test: /\.jsx?$/,
              use: {
                  loader: 'babel-loader',
                  options: {
                      presets: ["@babel/preset-env"],
                      plugins: [
                          [
                              "@babel/plugin-transform-runtime",
                              {
                                  "corejs": 3
                              }
                          ]
                      ]
                  }
              },
              exclude: /node_modules/
          },
          {
            //看清楚啦  這裡有四個loaderloader 的执行顺序是从右向左执行的,也就是后面的 loader 先执行,上面 loader 的执行顺序为: less-loader ---> postcss-loader ---> css-loader ---> style-loader
            test: /\.(le|c)ss$/,
            use: [ 
              'style-loader', 'css-loader', 
              {
                loader: 'postcss-loader',
                options: {
                  plugins: function () {
                    return [
                      require('autoprefixer')({
                        'overrideBrowserslist':[
                          '>0.25%','not dead'
                        ]
                      })
                    ]
                  }
                }
              }, 'less-loader'],
              exclude: /node_modules/
          },
          {
            test: /\.(png|jpg|gif|jpeg|webp|svg|eot|gltf|ttf|woff|woff2)$/,
            use: [
                {
                    loader: 'url-loader',
                    // options: {
                    //     limit: 10240, //10K
                    //     esModule: false 
                    // }
                    // ,
                    // 使用上面的那一段運行後會把圖片名字改為MD5哈希值,使用下面的會保留原有名稱加上六位哈希值
                    options: {
                      limit: 10240, //10K
                      // publicPath: './src/',
                      esModule: false,
                      name: '[name]_[hash:0].[ext]',
                      outputPath: 'assets' //這個可以將打包後的資源放到指定的文件夾下
                  }
                }
            ],
            exclude: /node_modules/
          }
          // {
          //   test: /\.html$/,
          //   use: 'html-withimg-loader'
          // },
      ]
  },
  plugins: [
    // 數組,放著所有的webpack插件
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html',
      config: config.template, //html-webpack-plugin 的 config 的妙用4-4
      minify: {
        removeAttributeQuotes: false ,//是否刪除屬性的雙引號
        collapseWhitespace: false, //是否折疊空白
      },
      hash: true //是否加上hash,默認是false
    }),
    new CleanWebpackPlugin(), //清理dist目錄插件,不需要傳參數,它自己可以找到outPath
    // new CleanWebpackPlugin({cleanOnceBeforeBuildPatterns:['**/*','!dll','!dll/**']}) //如果你有需要不刪除dll目錄下的文件的話可以這樣子寫
  ],
  devServer: {
    port: '8080', //默認是8080
    quiet: false, //默認不啟動
    inline: true, // 默認開啟inline 模式,如果設置為false, 開啟 iframe模式
    stats: 'errors-only', //終端僅僅打印 error
    overlay: false, //默認不啟用
    clientLogLevel: 'silent', //日誌等級
    compress: true //是否啟用gzip壓縮
  },
  devtool: 'cheap-module-eval-source-map' //开发环境下使用
}

// 在webpack中配置 babel,如果沒有額外的.babelrc配置的話就可以使用這段代碼2

index.less 图片可以正常显示到页面

@color: red;
body{
  div{
    color: @color;
    transition: all 2s;
  }
  background: url('./assets/img/mya.png');
  .panel {
    border: 0;
    width: 400px;
    font-size: 30px;
    line-height: 31px;
    text-indent: 20px;
  }
  body,#webglCanvas {
    width: 100%;
    height: 100vh;
    overflow: hidden;
  }
}

js里的写法如下

 const { texture: texture5, mesh: mesh5 } = await aaaaaa(
    { url: '../assets/img/testImg/testpng/color2.png' },
    [[-1500, -5, 1500], [900, -5, -400]]
  );

解决方案如下:

1.执行命令npm i copy-webpack-plugin --save
这里需要注意的是: 这个包存在兼容问题,可能会报错:compilation.getCache is not a function,如果报错就换个版本就行了,尝试执行npm i copy-webpack-plugin@6.0.2 --save
2.进入webpack.config.js里,添加如下代码


const CopyWebpackPlugin = require('copy-webpack-plugin');
new CopyWebpackPlugin({
      patterns: [
        {
          from: 'src/assets/',
          to: 'assets/'
        },
      ],
    })

重新启动,OK啦~~

posted @ 2021-01-30 15:32  糖~豆豆  阅读(845)  评论(0编辑  收藏  举报
Live2D