Skip to content

Webpack Loader 与 Babel ​

Babel 处理 JS ​

基础配置 ​

bash
yarn add babel-loader @babel/core @babel/preset-env -D
yarn add babel-loader @babel/core @babel/preset-env -D
js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: { presets: ['@babel/preset-env'] },
        },
        include: path.resolve(__dirname, 'src'),
        exclude: /node_modules/,
      },
    ],
  },
}
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: { presets: ['@babel/preset-env'] },
        },
        include: path.resolve(__dirname, 'src'),
        exclude: /node_modules/,
      },
    ],
  },
}

处理 Class 语法 ​

bash
yarn add @babel/plugin-proposal-class-properties -D
yarn add @babel/plugin-proposal-class-properties -D
js
options: {
  presets: ['@babel/preset-env'],
  plugins: ['@babel/plugin-proposal-class-properties'],
}
options: {
  presets: ['@babel/preset-env'],
  plugins: ['@babel/plugin-proposal-class-properties'],
}

装饰器 ​

bash
yarn add @babel/plugin-proposal-decorators -D
yarn add @babel/plugin-proposal-decorators -D
json
{
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}
{
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

transform-runtime(抽离公共代码) ​

bash
yarn add @babel/plugin-transform-runtime -D
yarn add @babel/runtime -S  # 生产依赖
yarn add @babel/plugin-transform-runtime -D
yarn add @babel/runtime -S  # 生产依赖
json
{ "plugins": ["@babel/plugin-transform-runtime"] }
{ "plugins": ["@babel/plugin-transform-runtime"] }

Polyfill(ES7 语法) ​

bash
yarn add @babel/polyfill
yarn add @babel/polyfill
js
require('@babel/polyfill')
'aaa'.includes('aa')
require('@babel/polyfill')
'aaa'.includes('aa')

Babel + TypeScript ​

bash
npm i @babel/{cli,core,preset-env,preset-react,preset-typescript} babel-loader -D
npm i @babel/{cli,core,preset-env,preset-react,preset-typescript} babel-loader -D
json
// .babelrc
{
  "presets": [
    ["@babel/env", { "targets": { "node": 6 } }],
    "@babel/preset-react",
    "@babel/typescript"
  ]
}
// .babelrc
{
  "presets": [
    ["@babel/env", { "targets": { "node": 6 } }],
    "@babel/preset-react",
    "@babel/typescript"
  ]
}
js
// webpack.config.js
{ test: /\.tsx?$/, use: 'babel-loader', exclude: /node_modules/ }
// webpack.config.js
{ test: /\.tsx?$/, use: 'babel-loader', exclude: /node_modules/ }

Babel + Lodash 按需引入 ​

bash
npm i babel-plugin-lodash lodash-webpack-plugin -D
npm i babel-plugin-lodash lodash-webpack-plugin -D
json
// .babelrc
{ "plugins": ["lodash"] }
// .babelrc
{ "plugins": ["lodash"] }
js
// webpack.config.js
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
plugins: [new LodashModuleReplacementPlugin()]
// webpack.config.js
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
plugins: [new LodashModuleReplacementPlugin()]

PostCSS 自动添加兼容前缀 ​

bash
yarn add postcss-loader autoprefixer -D
yarn add postcss-loader autoprefixer -D
js
rules: [
  {
    test: /\.css$/,
    use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
  },
]
rules: [
  {
    test: /\.css$/,
    use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
  },
]

根目录创建 postcss.config.js:

js
module.exports = {
  plugins: [require('autoprefixer')],
}
module.exports = {
  plugins: [require('autoprefixer')],
}

MiniCssExtractPlugin(CSS 抽离成单文件) ​

bash
yarn add mini-css-extract-plugin -D
yarn add mini-css-extract-plugin -D
js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          { loader: MiniCssExtractPlugin.loader, options: { esModule: false } },
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: 'main.css' }),
  ],
}
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          { loader: MiniCssExtractPlugin.loader, options: { esModule: false } },
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: 'main.css' }),
  ],
}

ESLint ​

bash
npm i eslint-webpack-plugin -D
npm i eslint-webpack-plugin -D
js
const ESLintPlugin = require('eslint-webpack-plugin')
module.exports = {
  plugins: [new ESLintPlugin(options)],
}
const ESLintPlugin = require('eslint-webpack-plugin')
module.exports = {
  plugins: [new ESLintPlugin(options)],
}

图片打包 ​

file-loader(解析 JS 中的图片) ​

bash
yarn add file-loader -D
yarn add file-loader -D
js
{ test: /\.(png|jpg|gif)$/, use: 'file-loader' }
{ test: /\.(png|jpg|gif)$/, use: 'file-loader' }

图片必须使用 require 或 import 导入才会被打包

html-withimg-loader(解析 HTML 标签中的图片) ​

bash
yarn add html-withimg-loader -D
yarn add html-withimg-loader -D
js
{ test: /\.html$/, use: 'html-withimg-loader' }
{ test: /\.html$/, use: 'html-withimg-loader' }

url-loader(Base64 转换) ​

bash
yarn add url-loader -D
yarn add url-loader -D
js
{
  test: /\.(png|jpg|gif)$/,
  use: {
    loader: 'url-loader',
    options: {
      limit: 200 * 1024, // 小于 200k 转 base64
      outputPath: '/img/',
      fallback: 'file-loader', // 超过 200k 用 file-loader
    },
  },
}
{
  test: /\.(png|jpg|gif)$/,
  use: {
    loader: 'url-loader',
    options: {
      limit: 200 * 1024, // 小于 200k 转 base64
      outputPath: '/img/',
      fallback: 'file-loader', // 超过 200k 用 file-loader
    },
  },
}

图片优化 ​

bash
# 压缩图片
yarn add imagemin-webpack-plugin -D
# 雪碧图
yarn add webpack-spritesmith -D
# 压缩图片
yarn add imagemin-webpack-plugin -D
# 雪碧图
yarn add webpack-spritesmith -D

暴露全局变量 ​

expose-loader ​

bash
yarn add expose-loader -D
yarn add expose-loader -D
js
{
  test: require.resolve('jquery'),
  use: 'expose-loader?$', // 将 jquery 作为 $ 挂载到全局
}
{
  test: require.resolve('jquery'),
  use: 'expose-loader?$', // 将 jquery 作为 $ 挂载到全局
}

ProvidePlugin(在每个模块注入) ​

js
const webpack = require('webpack')
module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery', // 项目中可直接使用 $ 符
    }),
  ],
}
const webpack = require('webpack')
module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery', // 项目中可直接使用 $ 符
    }),
  ],
}

打包文件分类 ​

js
// 在 loader 中加路径前缀
{ loader: 'file-loader', options: { outputPath: '/img/' } }

// 给所有资源加统一 CDN 地址
output: { publicPath: 'http://cdn.example.com' }

// 给单独 loader 加 CDN 地址
{ loader: 'file-loader', options: { publicPath: 'http://cdn.example.com' } }
// 在 loader 中加路径前缀
{ loader: 'file-loader', options: { outputPath: '/img/' } }

// 给所有资源加统一 CDN 地址
output: { publicPath: 'http://cdn.example.com' }

// 给单独 loader 加 CDN 地址
{ loader: 'file-loader', options: { publicPath: 'http://cdn.example.com' } }