• 3

  • 449

  • Favorite

31. webpack 入门使用

智能的司机

我是老司机

2 months ago

31.1 目标一: 编译js文件

本地运行webpack, 或者npx

  1. 安装:

    npm install --global webpack@4 webpack-cli@4
    复制代码
  2. 建立测试文件:/page.html,

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>ky</title>
    </head>
    <body>
    hah
    <script src="dist/bundle.js"></script>
    </body>
       
    </html>
    复制代码

    /src/index.js:

    import la from './bab'
       
    console.log(la)
    复制代码

    /src/bab.js:

    export default "lala"
    复制代码
  3. 设置配置文件:

    const path = require('path');
       
    module.exports = {
        //设置为开发者模式, 用于消除开始的warning
        mode: "development",  
        //设置入口: 也就是要转换的文件
        entry: './src/index.js', 
        //设置出口: 也就是生成的文件
        output: {
            //path一定是绝对路径
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js',
        },
    };
    复制代码
  4. 运行shell命令, 生成js文件:

    npm init -y
    webpack
    复制代码

***webpack的作用:***分析,将现有js代码, 变成能够在大多数, 以及低版本浏览器运行的js代码

31.2 目标二: 理解文件名的hash的用途


什么是http缓存?

一个页面加载的资源, 有的从服务器获取, 有的从本地http缓存直接加载.

分辨某个资源是否缓存, 看cache-control属性

如下图的:

cache-control: max-age=2592000: 这个资源保存在本地, 最多保存30天

cache-control: no-cache: 这个资源不缓存.


文件名hash的作用?

文件同,就取不同的hash名, 告诉浏览器这是一个不同的文件,需要重新请求.

具体用法如下:

module.exports = {
    mode: "development",
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        // [contenthash]就是一个hash值
        filename: 'bundle.[contenthash].js',
    },
};
复制代码

entry: './src/index.js',文件没有改变的时候, 不管重复多少次webpack, 都不会调用hash,生成不同js文件

entry: './src/index.js,文件改变的时候, 就会调用[contenthash]生成新的js文件

如何设置简单的shell命令: 先删文件, 再编译

package.json文件中,设置:

{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
      //加上这句话
    "build": "rm -rf ./dist && webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

复制代码

31.3 目标三: 自动生成html文件

遇见了错误::

Cannot read property 'tap' of undefined

原因: webpack 以及webpack-cli 和html-webpack-plugin版本不一致, 全部升级到最新版本就好


自动生成html的步骤:

  1. yarn add html-webpack-plugin --dev
    复制代码
  2. 修改配置文件:

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const path = require('path');
       
    module.exports = {
      entry: 'index.js',
      output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'index_bundle.js',
      },
      plugins: [new HtmlWebpackPlugin()],
    };
    复制代码

31.4 目标四: 引入css

  1. yarn add css-loader style-loader --dev
    复制代码
  2. webpack.config.js

    module.exports = {
      module: {
        rules: [
          {
            test: /\.css$/i,
               
              //下面一句话: 用css-loader加载.css文件, 用style-loader将css文件放到html页面中去
            use: ["style-loader", "css-loader"],
          },
        ],
      },
    };
    复制代码

两种方法

31.5 目标五: 用webpack-dev-server 代替hs

he webpack-dev-server provides you with a simple web server and the ability to use live reloading. Let's set it up:

yarn add --dev webpack-dev-server
复制代码

Change your configuration file to tell the dev server where to look for files:

webpack.config.js

 const path = require('path');
 const HtmlWebpackPlugin = require('html-webpack-plugin');
 const { CleanWebpackPlugin } = require('clean-webpack-plugin');

 module.exports = {
   mode: 'development',
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
   devtool: 'inline-source-map',
+  devServer: {
+    contentBase: './dist',
+  },
   plugins: [
     new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
     new HtmlWebpackPlugin({
       title: 'Development',
     }),
   ],
   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
 };
复制代码

package.json

 {
   "name": "webpack-demo",
   "version": "1.0.0",
   "description": "",
   "private": true,
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
     "watch": "webpack --watch",
+    "start": "webpack serve --open",
     "build": "webpack"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "devDependencies": {
     "clean-webpack-plugin": "^3.0.0",
     "html-webpack-plugin": "^4.5.0",
     "webpack": "^5.4.0",
     "webpack-cli": "^4.2.0",
     "webpack-dev-server": "^3.11.0"
   },
   "dependencies": {
     "lodash": "^4.17.20"
   }
 }
复制代码

不依赖dist文件, 之间内存中走,

31.6 目标六: 使用两个webpack config文件

直接复制config文件, 然后修改yarn build命令

  "scripts": {
      
      //--config 引用新的入口
    "build": "rm -rf ./dist && webpack --config webpack.config.prod.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack serve --open"
  },
复制代码

如何用继承的方法实现使用两个config文件?

建立一个webpack.config.base.js文件: 用来放公共的配置

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[contenthash].js',
    },
    plugins: [new HtmlWebpackPlugin({
        title: "Webpack App",
        template: "src/index.html"
    }), new MiniCssExtractPlugin()],
    devServer: {
        contentBase: './dist',
    },
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: ["style-loader", "css-loader"],
            },
        ],
    }
};
复制代码

用继承的方法来使用开发配置文件webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const base = require("./webpack.config.base.js")
module.exports = {
    ...base,
    mode: "development",
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [MiniCssExtractPlugin.loader, "css-loader"],
            },
        ],
    }
};
复制代码

用继承的方法使用生产配置文件webpack.config.prod.js

const base = require("./webpack.config.base.js")
module.exports = {
    ...base,
    mode: "production",
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: ["style-loader", "css-loader"],
            },
        ],
    }
};
复制代码
免责声明:文章版权归原作者所有,其内容与观点不代表Unitimes立场,亦不构成任何投资意见或建议。

CSS

449

Relevant articles

未登录头像

No more data