详解webpack4.x之搭建前端开发环境(2)

devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, host: '0.0.0.0', port: 9000, hot: true, //是否热更新 proxy: { //代理 '/api': 'http://localhost:3000' } }

package.json中启动命令配置如下:

"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --mode development", "build": "webpack --mode production" }

执行npm run start,执行结果如下:

详解webpack4.x之搭建前端开发环境

这样开发环境我们的主要配置就完成了,但是当我们用uglifyjs压缩es6代码时,会发现会报错,因为uglifyjs不能压缩es6的代码,此时我们需要手动配置下babel,具体步骤如下:

1、安装项目依赖

npm install @babel/core @babel/preset-env -D

2、新建在项目根目录下 .babelrc 文件,填入以下配置信息

{ "presets":["@babel/preset-env"] }

执行npm run build,压缩项目代码,结果如下:

详解webpack4.x之搭建前端开发环境

全部代码:

const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const CleanWebpackPlugin = require('clean-webpack-plugin'); const config = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[hash].min.js' }, module: { rules: [{ test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }) }, { test: /\.js/, exclude: /node_modules/, //过滤node_modules文件夹 use: [{ loader: 'babel-loader' }] } ] }, optimization: { splitChunks: { name: "vendor", filename: 'vendor-[hash].min.js' }, minimizer: [new UglifyJsPlugin()] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }), new ExtractTextPlugin({ filename: 'build.min.css', allChunks: true, }), new webpack.BannerPlugin({ banner: `构建时间:${new Date().getFullYear()}-${new Date().getMonth()+1}-${new Date().getDate()}` }), new CleanWebpackPlugin(), // new webpack.EnvironmentPlugin({ NODE_ENV: 'production' }), new BundleAnalyzerPlugin() ], devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, host: '0.0.0.0', port: 9000, hot: true, //是否热更新 proxy: { //代理 '/api': 'http://localhost:3000' } }, devtool: 'source-map' }; module.exports = config;

参考资料:

webpack中文网: https://www.webpackjs.com

webpack内置插件列表: https://www.webpackjs.com/plugins/

第三方插件可自行搜索npm: https://www.npmjs.com/

项目源码:https://github.com/gerryli0214/webpack-demo

文笔比较粗糙,如有问题,烦请指出,谢谢!以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/9a83a135559f554d4def8059090cf97c.html