webpack6-babel的基本使用
一、Babel有什么用?
因为webpack默认只支持部分的ES6代码,为了使用ES6更高级的代码(如class),用Babel实现
二、使用Babel需要的包
npm i babel-core babel-loader babel-plugin-transform-runtime -D
npm i babel-preset-env babel-preset-stage-0 -D
三、babel的配置文件
配置文件名: .babelrc
配置文件内容:
{
"presets": [],
"plugins": []
}
注意: .babelrc 配置文件内容为json格式,plugins填插件名(去掉babel-plugin-前缀),presets填预设名(去掉babel-preset-前缀)
四、在webpack.config.js配置文件中添加一个rules规则
{test: /\.js$/, use: 'babel-loader', exclude: /node_modules/}
五、步骤
-
npm初始化
npm init -y
-
安装
npm i webpack webpack-cli webpack-dev-server -D npm i jquery html-webpack-plugin -S
-
安装babel
npm i babel-core babel-loader babel-plugin-transform-runtime -D npm i babel-preset-env babel-preset-stage-0 -D
-
配置babel
新建配置文件:.babelrc
文件内容:{ "presets": ["env", "stage-0"], "plugins": ["transform-runtime"] }
-
编写配置文件 webpack.config.js
const path = require('path') const webpack = require('webpack') const htmlwebpackplugin = require('html-webpack-plugin') module.exports = { entry: path.join(__dirname, "./src/js/index.js"), output: { path: path.join(__dirname, "./dist"), filename: "index.js" }, mode: "development", devServer: { open: true, port: 3000, contentBase: "src", hot: true }, plugins: [ new webpack.HotModuleReplacementPlugin(), new htmlwebpackplugin({ template: "./src/index.html", filename: "index.html" }) ], module: { rules: [ {test: /\.js$/, use: 'babel-loader', exclude: /node_modules/} ] } }
-
编写js文件
import $ from 'jquery' $(function () { $("li:odd").css("color", "pink") $("li:even").css("color", "skyblue") }) class Student { static name = "seven" } console.log(new Student())
-
编写html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>这是第1个li</li> <li>这是第2个li</li> <li>这是第3个li</li> <li>这是第4个li</li> <li>这是第5个li</li> </ul> </body> </html>
-
在package.json中添加
"dev": "webpack-dev-server"
-
运行
npm run dev
更新时间:2020-1-2