學習webpack4.x - ES6語法轉化
...持續中
=======================================================
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, 成功!如下圖: