image.png

webpack

const path = require(‘path’);
const { CleanWebpackPlugin } = require(‘clean-webpack-plugin’);
const HtmlWebpackPlugin = require(‘html-webpack-plugin’);
const webpack = require(‘webpack’);

module.exports = {
entry: ‘./src/index.js’,
output: {
publicPath: “/“,
filename: ‘bundle.js’,
path: path.resolve(dirname, ‘dist’)
},
devServer: {
contentBase: “./dist”,//path.join(
dirname, ‘dist’),
open: true, //自动打开
hot: true,
inline: true
// port: 8000, //默认8080
// proxy: { //接口请求反向代理配置
// “/api”: “http://localhost:3000
// }
},
module: {
rules: [
{
test: /.(jpg|png|gif)$/,
use: {
loader: ‘url-loader’,
options: {
name: ‘[name].[ext]’, //官网解释[ext]这种是占位符
outputPath: ‘images/‘,
limit: 10240 //限制大小30kb因为这个图片26kb
}
}
},
{
test: /.scss$/,
use: [
‘style-loader’,
‘css-loader’,
‘sass-loader’
]
},
{
test: /.css$/,
use: [
‘style-loader’,
‘css-loader’
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: ‘./src/index.html’,
filename: ‘index.html’, //可不设置 默认index.html
// minify:{
// removeAttributeQuotes:true,//去除引号
// removeComments:true,//去除注释
// removeEmptyAttributes:true,//去除空属性
// collapseWhitespace:true//去除空格
// }
}),
new webpack.HotModuleReplacementPlugin()
],
devtool: ‘cheap-module-eval-source-map’
}

index.js


import ‘./index.scss’;
import ‘./index.css’;
import count from ‘./count.js’;
import print from ‘./print.js’;

// const btn = document.createElement(‘button’);
// btn.innerHTML = ‘添加’;
// document.body.appendChild(btn);

// btn.onclick = function() {
// const div = document.createElement(‘div’);
// div.innerHTML = ‘div’;
// document.body.appendChild(div);
// };

count()
print()

if (module.hot) {
module.hot.accept(‘./count.js’, function() {
document.body.removeChild(document.getElementById(‘count’))
count();
})
}

count.js

export default function count() {
const btn = document.createElement(‘button’);
btn.id = ‘count’
btn.innerHTML = ‘静态’;
document.body.appendChild(btn);
}

print.js

export default function print() {
const btn = document.createElement(‘button’);
btn.innerHTML = ‘添加’;
document.body.appendChild(btn);

  1. btn.onclick = function() {<br /> const div = document.createElement('div');<br /> div.innerHTML = 'div';<br /> document.body.appendChild(div);<br /> };<br />}


index.css

button {
color: blue;
}
div {
color: red;
}