一.用file-loader编译不同后缀的图片
1.配置webpeck.config.js文件
const path = require(‘path‘); const htmlWebpackPlugin = require(‘html-webpack-plugin‘); module.exports={//node.js语法导出一个对象 entry:‘./src/app.js‘, output:{ path:path.resolve(__dirname,‘dist‘),//绝对路径 filename:‘main.js‘, }, plugins:[//生成html new htmlWebpackPlugin({ filename:‘index.html‘, template:‘src/index.html‘ }) ], module:{ rules:[{ test:/\.js$/, use:[{ loader:‘babel-loader‘, options:{ presets:[‘react‘] } },]}, { test:/\.css$/, use:[‘style-loader‘,‘css-loader‘] }, { test:/\.(jpg|png|gif|jpeg)$/, use:[‘file-loader‘] }, ] }, devServer:{ open:true,//自动打开服务器首页 port:9000, inline:true, } }
2.在app.js文件中引入
import React from ‘React‘; import ReactDOM from ‘react-dom‘; import ‘./common/css/style.css‘; import ‘./common/css/app.css‘; import tu from ‘./common/img/11.jpg‘; const tu2 = require(‘./common/img/1.png‘);//全局方式引用 ReactDOM.render( <div className=‘rea‘> <img src={tu} alt=""/> <img src={tu2} /> <img src={require(‘./common/img/1.png‘)} />//直接使用 </div>, document.getElementById(‘cdd‘) );
二、用url-loader编译不同后缀的文件
1.配置url-loader,url-loader会将引入的图片编码,生成dataURl,小于约20Kb的图片生成打他URL
const path = require(‘path‘); const htmlWebpackPlugin = require(‘html-webpack-plugin‘); module.exports={//node.js语法导出一个对象 entry:‘./src/app.js‘, output:{ path:path.resolve(__dirname,‘dist‘),//绝对路径 filename:‘main.js‘, }, plugins:[//生成html new htmlWebpackPlugin({ filename:‘index.html‘, template:‘src/index.html‘ }) ], module:{ rules:[{ test:/\.js$/, use:[{ loader:‘babel-loader‘, options:{ presets:[‘react‘] } },]}, { test:/\.css$/, use:[‘style-loader‘,‘css-loader‘] }, { test:/\.(jpg|png|gif|jpeg)$/, use:[{ loader:‘url-loader‘, options:{ limit:20000 } }] }, ] }, devServer:{ open:true,//自动打开服务器首页 port:9000, inline:true, } }
2.引入图片
import React from ‘React‘; import ReactDOM from ‘react-dom‘; import ‘./common/css/style.css‘; import ‘./common/css/app.css‘; import tu from ‘./common/img/11.jpg‘; import img2 from ‘./common/img/2.jpg‘; const tu2 = require(‘./common/img/1.png‘); ReactDOM.render( <div className=‘rea‘> <img src={tu} /> <img src={tu2} /> <img src={img2}/> <img src={require(‘./common/img/1.png‘)} /> </div>, document.getElementById(‘cdd‘) );
3. 运行 cnpm run dev,展示图片使用状况