學(xué)習(xí)webpack4 - 基礎(chǔ)配置
學(xué)習(xí)webpack4 - HTML處理
學(xué)習(xí)webpack4 - 樣式處理
學(xué)習(xí)webpack4 - ES6語法轉(zhuǎn)化
學(xué)習(xí)webpack4 - 第三方庫的使用
學(xué)習(xí)webpack4 - 抽離公共代碼
...持續(xù)中
=======================================================
ES6語法轉(zhuǎn)化
注意:開始之前以下內(nèi)容之前,需要配置一些webpack的基礎(chǔ)配置,傳送門:學(xué)習(xí)webpack4.x - 基礎(chǔ)配置
當(dāng)前目錄結(jié)構(gòu)為:
require('./index.css');
require('./index.scss');
- webpack.config.js文件內(nèi)容:
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'); //優(yōu)化項,比如壓縮css等
let UglifyJsPlugin = require('uglifyjs-webpack-plugin'); //壓縮jsmodule.exports = {// mode: 'development',//優(yōu)化項配置optimization: {minimizer: [new OptimizeCssPlugin(),new UglifyJsPlugin({cache: true, //緩存parallel: true, //并發(fā)打包sourceMap: true //源碼映射便于調(diào)試})]},//開一個本地服務(wù)devServer: {port: 3000, //端口號progress: true, //進(jìn)度條contentBase: './dist', //指定目錄運行服務(wù)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文件名稱})]
}
{"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轉(zhuǎn)化為ES5
step1: 打開src/index.js,輸入:
const fn = () => {console.log('丸子');
}fn ();
step2: 配置webpack.config.js文件:
將ES6轉(zhuǎn)成ES5,需要babel-loader,配置規(guī)則為:
module.exports = {//...module: {//...{test: /\.js$/,use: {loader: 'babel-loader',options: {presets: ['@babel/preset-env'] // 根據(jù)目標(biāo)瀏覽器自動轉(zhuǎn)換為相應(yīng)es5代碼}}}}
};
step3: 安裝插件:
yarn add babel-loader @babel/core @babel/preset-env -D
嘗試運行: npm run dev, 成功!如下圖:
總結(jié)
以上是生活随笔為你收集整理的学习webpack4 - ES6语法转化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。