• webpack 4 关于图片需要使用 file-loader 和 url-loader。
    • webpack 5 不需要
      • file-loader => asset/resource 把图片拷贝到输出目录里去,返回一个输出路径,包括文件
      • url-loader => asset/inline 不拷贝文件,直接把源文件变成 base 64 字符串内嵌到输出结果

    使用如下:

    1. /** ./src/index.js **/
    2. import url from './test.jpeg';
    3. let image = new Image();
    4. image.src = url;
    5. document.body.append(image);
    1. /** ./webpack.config.js **/
    2. const path = require('path');
    3. const webpack = require('webpack');
    4. const HtmlWebpackPlugin = require('html-webpack-plugin');
    5. module.exports = {
    6. devServer: {
    7. port: 8080,
    8. open: true,
    9. compress: true,
    10. static: './dist',
    11. },
    12. entry: {
    13. index: './src/index.js'
    14. },
    15. output:{
    16. path: path.resolve(__dirname, './dist'),
    17. filename: '[name].[hash:8].js'
    18. },
    19. resolve:{
    20. alias: {
    21. '@':path.resolve('src')
    22. }
    23. },
    24. module:{
    25. rules: [
    26. {
    27. test: /\.css$/,
    28. use:[
    29. 'style-loader',
    30. {
    31. loader:'css-loader',
    32. },
    33. 'postcss-loader'
    34. ]
    35. },
    36. {
    37. test:/\.(jpeg|jpg|png|gif)$/,
    38. type:'asset/resource',
    39. generator:{
    40. filename:'[hash][ext]'
    41. }
    42. }
    43. ]
    44. },
    45. plugins: [
    46. new webpack.CleanPlugin(),
    47. new HtmlWebpackPlugin({
    48. filename:'index.html',
    49. inject: 'body',
    50. template:'./public/index.html'
    51. })
    52. ]
    53. }

    如果想要转换成base64, 将 resource 改成 inline 就可以了。