1. 程式人生 > 其它 >webpac的配置以及webpack中babel的配置

webpac的配置以及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 // 參考官方文件
}
]
],
}
```