前提:在项目的根目录下
1.通过 npm install 初始化项目,安装相关包
2.通过 npm run webpack 打包项目,则会对应生成相应的文件
效果图:
源码:
index.js
import './index.css';
//引入图片
import img from './img/logo.png';
console.log(img);
//创建 img 元素
const imgEl = document.createElement('img');
// 将路径加到img元素的src属性上
imgEl.src = img;
// 将 img 元素加到页面里
document.body.appendChild(imgEl);
index.css
body {
background-color: yellow;
}
package.json
{
"name": "webpack-js-img",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"webpack": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^4.1.1",
"file-loader": "^6.0.0",
"html-webpack-plugin": "^4.3.0",
"mini-css-extract-plugin": "^0.9.0",
"style-loader": "^1.2.1",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
},
'css-loader'
]
},
{
test: /\.(jpg|png|gif)$/,
use: {
loader: 'file-loader',
options: {
name: 'img/[name].[ext]',
esModule: false
}
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html'
}),
new MiniCssExtractPlugin({
filename: 'css/[name].css'
})
]
};