如何将图像与Webpack捆绑在一起?

问题描述:

我跟随webpack2指南asset managing,一切都很好,但.. 当我添加我的图像时,它作为一个单独的文件旁边的dist文件夹中的bundle.js,因为没有引用index.html形象它抛出一个错误文件没有找到。 我在想,图像将在bundle.js :(如何将图像与Webpack捆绑在一起?

所以现在我怎么可以使用带有的WebPack请图像内部handeled ..

这里是我的文件夹结构:

dist 
     bundel.js 
     4942b81d7881a9d50c8984802eed28be.png 
    node_modues 
    src 
     css 
      style.css 
     js 
      app.js 
      content.js 
     images 
      icon.png 
    index.html 
    package.json 
    webpack.config.js 

我app.js:

const content = require("./content.js"); 
    import _ from 'lodash'; 
    import '../css/style.css' 
    import icon from '../images/icon.png'; 

    document.write(content); 
    console.log('Hello world!'); 

    /* Lodash */ 
    function component() { 
     var element = document.createElement('div'); 

     element.innerHTML = _.join(['Hello', 'webpack'], ' '); 
     element.classList.add('hello'); 

     var myIMG = new Image(); 
     myIMG.src = icon; 
     element.appendChild(myIMG); 

     return element; 
    } 

    document.body.appendChild(component()); 

style.js:

body { 
     background: #bada55; 
    } 

    .hello { 
     color: red; 
     background: url('../images/icon.png'); 
     } 

webpack.config.js:

const path = require('path'); 

    module.exports = { 
     entry: "./src/js/app.js", 

     output: { 
      filename: 'bundle.js', 
      path: path.resolve(__dirname, 'dist') 
     }, 

     module: { 
      rules: [ 
       { 
        test: /\.css$/, 
        use: [ 
        'style-loader', 
        'css-loader' 
        ] 
       }, 
       { 
        test: /\.(png|jpg|jpeg|svg|gif)$/, 
        use: [ 
         'file-loader' 
        ] 
       } 
      ] 
     } 


    }; 

的package.json:

{ 
     "name": "letsLearnES6", 
     "version": "1.0.0", 
     "description": "", 
     "main": "app.js", 
     "scripts": { 
     "build": "webpack" 
     }, 
     "keywords": [], 
     "author": "", 
     "license": "ISC", 
     "devDependencies": { 
     "css-loader": "^0.28.7", 
     "file-loader": "^1.1.5", 
     "lodash": "^4.17.4", 
     "style-loader": "^0.19.0", 
     "webpack": "^3.6.0" 
     } 
    } 

错误:

GET file:///...Root_directory_path.../4942b81d7881a9d50c8984802eed28be.png net::ERR_FILE_NOT_FOUND 

这是因为图像已被移动通过的WebPack到:

file:///...Root_directory_path.../dist/4942b81d7881a9d50c8984802eed28be.png 

请帮帮忙,我会明白更多,如果有人能告诉MRE我在做什么错的,不同于Webpack guide page

预先感谢您。

+0

你的图像的什么路径被放入bundle.js文件中? – sergei

+0

请在我的问题结尾处看到我的更新 –

您应该将您的index.html文件移动到dist目录中,因为文件路径是相对于输出目录生成的。

此外,您可以使用HTML Webpack Plugin动态生成index.html文件,因为建议在资产文件名中使用散列以避免浏览器缓存问题。

+0

我试着在控制台中移动index.html ==>同样的错误 –

+0

另外,使用HTML Webpack Plugin不会解决问题,因为eroor中图像的引用是在根目录不是dist文件夹 –

+0

你是对的,index.html应该在dist文件夹内,我的坏..对不起,我来自gulp背景:(谢谢你 –