学习 webpack4.x – 基础配置学习 webpack4.x – HTML 处理学习 webpack4.x – 样式处理学习 webpack4.x – ES6 语法转化 // 学习 webpack4.x – 全局变量引入(未整理)// 学习 webpack4.x – 图片处理(未整理)
… 持续中
=======================================================
ES6 语法转化
注意:开始之前以下内容之前,需要配置一些 webpack 的基础配置,传送门:学习 webpack4.x – 基础配置
当前目录结构为:
index.js 文件内容:
require(‘./index.css’);
require(‘./index.scss’);
webpack.config.js 文件内容:
let path = require(‘path’);
let HtmlWebpackPlugin = require(‘html-webpack-plugin’);
let MiniCssExtractPlugin = require(‘mini-css-extract-plugin’); // 抽离 CSS
let OptimizeCssPlugin = require(‘optimize-css-assets-webpack-plugin’); // 优化项,比如压缩 css 等
let UglifyJsPlugin = require(‘uglifyjs-webpack-plugin’); // 压缩 js
module.exports = {
// mode: ‘development’,
// 优化项配置
optimization: {
minimizer: [
new OptimizeCssPlugin(),
new UglifyJsPlugin({
cache: true, // 缓存
parallel: true, // 并发打包
sourceMap: true // 源码映射便于调试
})
]
},
// 开一个本地服务
devServer: {
port: 3000, // 端口号
progress: true, // 进度条
contentBase: ‘./dist’, // 指定目录运行服务
open: true // 自动打开浏览器
},
entry: ‘./src/index.js’,
output: {
filename: ‘bundle.js’,
path: path.resolve(__dirname, ‘dist’)
},
// 模块配置
module: {
rules: [{
test: /\.(css|scss)$/,
use: [MiniCssExtractPlugin.loader, ‘css-loader’, ‘postcss-loader’, ‘sass-loader’]
}]
},
// 插件配置
plugins: [
new HtmlWebpackPlugin({
template: ‘./src/index.html’, // 原始文件
filename: ‘index.html’, // 打包后的文件名称
hash: true, //hash
}),
new MiniCssExtractPlugin({
filename: ‘main.css’ // 抽离出的 css 文件名称
})
]
}
package.json 文件内容:
{
“name”: “webpack”,
“version”: “1.0.0”,
“main”: “index.js”,
“license”: “MIT”,
“scripts”: {
“dev”: “webpack –mode development && webpack-dev-server”,
“build”: “webpack –mode production”
},
“devDependencies”: {
“autoprefixer”: “^9.4.7”,
“css-loader”: “^2.1.0”,
“html-webpack-plugin”: “^3.2.0”,
“less”: “^3.9.0”,
“less-loader”: “^4.1.0”,
“mini-css-extract-plugin”: “^0.5.0”,
“node-sass”: “^4.11.0”,
“optimize-css-assets-webpack-plugin”: “^5.0.1”,
“postcss-loader”: “^3.0.0”,
“sass-loader”: “^7.1.0”,
“style-loader”: “^0.23.1”,
“uglifyjs-webpack-plugin”: “^2.1.1”,
“webpack”: “^4.29.4”,
“webpack-cli”: “^3.2.3”,
“webpack-dev-server”: “^3.1.14”,
“webpack-html-plugin”: “^0.1.1”
}
}
将 ES6 转化为 ES5
step1: 打开 src/index.js,输入:
const fn = () => {
console.log(‘ 丸子 ’);
}
fn ();
step2: 配置 webpack.config.js 文件:
将 ES6 转成 ES5,需要 babel-loader,配置规则为:
module.exports = {
//…
module: {
//…
{
test: /\.js$/,
use: {
loader: ‘babel-loader’,
options: {
presets: [‘@babel/preset-env’] // 根据目标浏览器自动转换为相应 es5 代码
}
}
}
}
};
step3: 安装插件:
yarn add babel-loader @babel/core @babel/preset-env -D
尝试运行:npm run dev, 成功!如下图: