压缩 JS 文件: 这里把 mode 设置为 生产模式,就会自动压缩 JS 代码。
1.文件结构
2.代码
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>webpack</title> </head> <body> <h5>webpack</h5> </body> </html>
index.js
//第二种方式: 全部js兼容性处理 // import '@babel/polyfill' const add = (x, y)=> { return x + y; } console.log(add(1, 2)); const promise = new Promise((resolve)=>{ setTimeout(()=>{ console.log('定时器执行完毕') resolve() },1000) }) console.log("promise:",promise)
webpack.config.js
const {resolve} = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: './src/js/index.js', output: { filename: "js/built.js", path: resolve(__dirname, 'build') }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index.html" }) ], //生产环境下会自动压缩js代码 mode: "production" }
3.打包
$ webpack
4.预览
end~