webpack基础以及webpack中babel的配置

webpack 安装

  • npm 初始化,控制台输入
npm init -y
  • webpack 安装
npm i webpack webpack-cli -D

新建 webpack.config.js

const path = require('path')
module.exports = {
mode: "development",
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,"dist")
}
}

mode: 模式(可选:development,production)

entry: 入口文件

output: 打包输出文件(既打包到哪里)

在根目录新建 src/index.js

module.exports=function(){
return 2
}

package.json 配置启动

因为 webpack 不是全局安装的,所以不能使用 webpack 命令进行打包。可以在 package.json 中配置"build":"webpack":

{
"name": "webpackBabel",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build":"webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.59.1",
"webpack-cli": "^4.9.1"
}
}

到这里简单的 webpack 已经配置完成,在终端输入

npm run build

此时你就会发现多了个 dist/bundle.js 文件

/*
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
* This devtool is neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./src/index.js":
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/***/ ((module) => {
eval("module.exports=function(){\r\n return 2\r\n}\n\n//# sourceURL=webpack://webpackBabel/./src/index.js?");
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __webpack_require__("./src/index.js");
/******/
/******/ })()
;

这就是打包后的文件,webpack 默认自带 common.js 解析,可以直接打包

loader 配置

webpack 如果需要打包 css,img 等文件时候是需要借助 loader 配置,在 module 参数进行配置,以下用了几个常用 loader 配置:

const path = require('path')
module.exports = {
mode: "development",
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, "dist")
},
module: {
rules: [{
test: /\.css$/,
use: [
// [style-loader](/loaders/style-loader)
{ loader: 'style-loader' },
// [css-loader](/loaders/css-loader)
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}, {
test: /\.(jpg|png|gif)$/,
use: {
loader: 'url-loader',
options: {
name: '[name]_[hash].[ext]',
outputPath: 'images/',
limit: 10240 //如果图片大小小于10240则采用base64
}
}
}, {
test: /\.(eot|ttf|svg)$/,
use: {
loader: 'file-loader'
}
}]
}
}

loader 是需要进行安装的:

npm i url-loader file-loader url-loader css-loader style-loader -D

HtmlWebpackPlugin 插件的安装

安装 html-webpack-plugin

npm i html-webpack-plugin -D

html-webpack-plugin 插件可以在 dist 文件夹下生产一个 index.html 文件并且引入打包后的 js 文件

html-webpack-plugin 配置在 plugin 中:

...
const HtmlWebpackPlugin = require("html-webpack-plugin")
...
plugins: [
new HtmlWebpackPlugin()
]

执行 npm run build 后会发现 dist 文件下多了个 index.html 并且引入了 bundle.js

babel 的配置

  • 安装 babel
npm install --save-dev babel-loader @babel/preset-env @babel/core

配置 babel-loader:

module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,//不转换的文件
use: [{
loader: 'babel-loader'
}]
},
{
test: /\.css$/,
use: [
// [style-loader](/loaders/style-loader)
{ loader: 'style-loader' },
// [css-loader](/loaders/css-loader)
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
...
]
}
...
  • 新建.babelrc 文件
{
"presets": ["@babel/preset-env"]
}

src/index.js 写一个 es6 语法:

module.exports=function(){
const a = 1
return a
}

然后执行 npm run build ,就会发现 dist/bundle.js 里的 const 被转换成了 var,虽然有些语法可以进行转换,但是遇到如 promise 打包过后 promise 并不会被转换,所以此时就需要垫片(polyfill)

@babel/polyfill 的使用

处理类似 assign,includes,map,includes,promise 的垫片

  • 安装
npm i @babel/polyfill -s
  • babelrc 配置
{
"presets": [
[
"@babel/preset-env",
{
"debug": true,
"useBuiltIns": "usage"//usage表示按需引入polyfill,entry全部引入,false不引入
}
]
]
}

到这babel基本可以实现到es5的转换了。

runtime为开发组件而生

polyfill 问题是已经解决了,但是如果你是开发 一个 npm 组件,此时就不能用polyfill了,因为polyfill会污染全局变量,这时候就要用到一个插件@babel/plugin-transform-runtime

  • 安装
npm install --save @babel/runtime
npm install --save-dev @babel/plugin-transform-runtime
npm install --save @babel/runtime-corejs2 --save
  • .babelrc
{
"presets": [
[
"@babel/preset-env",
{
"debug": true,
"useBuiltIns": "false"
}
]
],
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"corejs": 2 // 参考官方文档
}
]
],
}