Webpack

[TOC]

WebPack

中文文档

局部


开发模式安装
npm install webpack webpack-cli --save-dev
yarn add webpack webpack-cli -D (-D换--save-dev也可以)
使用
./node_modules/.bin/webpack --version
npm 5以后可以
npx webpack --version
npx create-react-app 快速创建react app

全局

npm install webpack -g
yarn global add @vue/cli

可以在page.json 中配置scripts

"scripts": {
build: "webpack"
}

执行npm run build

输入输出

新建

webpack.config.js文件

const path = require('path')
// console.log(path.resolve())
// console.log(path.join(__dirname,'./dist'))
const config={
    entry: './src/index.js', //入口位置
    output: {
        filename: "bundle.js",
        path: path.join(__dirname,'./dist')//出口位置
    }
}

module.exports = config

引入node path模块 打开设置

引入


![图像 2020-2-4,上午11.27.jpg](https://upload-images.jianshu.io/upload_images/9175392-e4cacb98af86f9b7.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

增加的目录为

/Users/zhangzhuang/.nvm/versions/node/v10.16.0/lib/node_modules/npm/node_modules

path.join() 相当于拼接
__dirname 该项目的绝对路径
path.resolve() 该项目的绝对路径

Loaders

js 处理资源文件使用

安装

yarn add css-loader style-loader -D

webpack.config.js

module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader','css-loader','sass-loader']//顺序不能换,倒序执行
            }
        ]
    }

ssas支持

 yarn add sass-loader -D

webpack.config.js

rules: [
    {
        //sass-loader node-sass两个依赖都要安装
        test: /\.(scss|sass)$/,
        use: ['style-loader','css-loader','sass-loader']
    }
]

plugins

支柱功能,使WebPackage可扩展。

yarn add html-webpack-plugin -D

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')

const config = {
   ...
    plugins: [
        new HtmlWebpackPlugin({
                filename: 'index.html',
                template: 'template.html'
            }
        )
    ]
}

module.exports = config

热模块替换

webpack-dev-server配合使用,提供一个服务更新浏览器。

yarn add webpack-dev-server -D

package.json

  "scripts": {
    ...
    "watch": "webpack --watch",
    "hot": "webpack-dev-server"
  }

webpackage.config.js


const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack');

...
    devServer: {
        contentBase: path.join(__dirname, "src"),
        compress: true,
        port: 9006,
        hot: true
    },
    plugins: [
        new HtmlWebpackPlugin({
                filename: 'index.html',
                template: 'template.html'
            }
        ),
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ]

...

总结

关键词 总结
Loaders test去匹配文件、loader倒序加载流水线的处理
plugin的使用、热模块的替换 在plugins属性中new一个plugin
webpack-dev-server 引用HMR插件,修改js的时候,自动刷新页面

Mode

模式

选项 描述
development 开发模式
production 正式模式

webpack.config.js

const config = {
    mode: 'production'
    ....
}

基础使用 ,根据mode切host地址

index.js

if (process.env.NODE_ENV === 'development'){
    console.log('baseurl is localhost')
} else {
    console.log('baseurl is zz.com')
}

两个模式生成的bundle.js 是不同的

babel 配置css压缩

yarn add babel-loader  @babel/core @babel/preset-env  @babel/plugin-transform-runtime -D
yarn add @babel/runtime -S

.babelrc 只在软件包中有用

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

src/ a.js

export default () =>{
    console.log("come from module a")
}

index.js

import afn from './a'
afn()

成功引入

clean-webpack-plugin

清除文件

 yarn add clean-webpack-plugin  -D 

https://github.com/johnagan/clean-webpack-plugin

copy-webpack-plugin

 yarn copy-webpack-plugin -D

webpack.config.js

const CopyWebpackPlugin = require ('copy-webpack-plugin')
plugins: [
       ...
        new CopyWebpackPlugin([
            {
                from: path.join(__dirname,'assets'),
                to: 'assets'
            }
        ])
    ]

css和js压缩

https://webpack.js.org/plugins/mini-css-extract-plugin/#minimizing-for-production

yarn add terser-webpack-plugin optimize-css-assets-webpack-plugin mini-css-extract-plugin -D
  • Terser-webpack-plugin 压js
  • optimize-css-assets-webpack-plugin 压cs
  • mini-css-extract-plugin 支持头部引用

webpack.config.js

const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

你可能感兴趣的:(Webpack)