美文网首页
Webpack核心概念(二)

Webpack核心概念(二)

作者: 海到尽头天为岸 | 来源:发表于2019-05-31 15:43 被阅读0次
    Loader
    2.1 什么是Loader

    webpack可以使用 loader 来预处理文件,就是通过使用不同的Loader,webpack可以把不同的静态文件都编译成js文件,比如css,sass,less,ES6/7,vue,JSX等。

    使用Loader打包静态资源

    • 支持加载图片文件:
      需要安装 file-loader:解决CSS等文件中的引入图片路径问题
    npm install file-loader -D
    

    在 webpack.config.js 里添加 loader 配置

    module.exports = {
        //配置模块,主要用来配置不同文件的加载器
      module: {
          //配置模块规则
        rules: [
          {
            test: /\.(png|jpg|gif)$/, //正则匹配要使用相应loader的文件
            use: [
              {
                loader: 'file-loader', //要用到的loader
                  options: {
                      //palceholder占位符
                      name:'[name].[ext]', //打包后的图片名字,后缀和打包的之前的图片一样
                      outputPath: 'images/' //图片打包后的地址
                  },
              },
            ],
          },
        ],
      },
    };
    

    详细请看官方文档:file-loader

    • 将小图片转换成base64格式
      需要安装 url-loader:当图片小于limit的时候会把图片BASE64编码,大于limit参数的时候还是使用file-loader 进行拷贝
    npm install url-loader -D
    

    在 webpack.config.js 里添加 loader 配置

    module.exports = {
      module: {
        rules: [
          {
            test: /\.(png|jpg|gif|bmp/)$/i,
            use: [
              {
                loader: 'url-loader',
                options: {
                  name:'[name].[ext]',
                  outputPath: 'images/',
                  limit: 10240 //小于10k,就可以转化成base64格式。大于就会打包成文件格式
                }
              }
            ]
          }
        ]
      }
    }
    

    详细请看官方文档:url-loader

    • 支持加载样式CSS文件:
      需要安装 css-loader style-loader:
    npm install css-loader style-loader -D
    

    在 webpack.config.js 里添加 loader 配置

    //loader的执行顺序是从右向左,从下到上。css-loader:分析几个css文件之间的关系,最终合并为一个css。style-loader:在得到css生成的内容时,把其挂载到html的head里,成为内联样式。
    module.exports = {
      module: {
        rules: [
          {
            test: /\.css$/, //匹配以css为后缀的文件
            use: ['style-loader', 'css-loader'],
          },
        ],
      },
    };
    
    • 支持加载样式SASS文件:
      需要安装 sass-loader node-sass:
    npm install sass-loader node-sass -D
    

    在 webpack.config.js 里添加 loader 配置

    module.exports = {
        module: {
            rules: [{
                test: /\.scss$/,
                use: [
                    "style-loader", // 将 JS 字符串生成为 style 节点
                    "css-loader", // 将 CSS 转化成 CommonJS 模块
                    "sass-loader" // 将 Sass 编译成 CSS,默认使用 Node Sass
                ]
            }]
        }
    };
    
    • 为 css 样式属性加不同浏览器的前缀:
      为了浏览器的兼容性,有时候我们必须加入-webkit,-ms,-o,-moz这些前缀
      Trident内核:主要代表为IE浏览器, 前缀为-ms
      Gecko内核:主要代表为Firefox, 前缀为-moz
      Presto内核:主要代表为Opera, 前缀为-o
      Webkit内核:产要代表为Chrome和Safari, 前缀为-webkit
    npm i postcss-loader autoprefixer -D
    

    在项目跟目录下创建 postcss.config.js

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

    webpack.config.js

    module.exports = {
        module: {
            rules: [{
                test: /\.scss$/,
                use: [
                    "style-loader", // 将 JS 字符串生成为 style 节点
                    "css-loader", // 将 CSS 转化成 CommonJS 模块
                    'postcss-loader',//注意postcss-loader放置位置,应放在css-loader之后,sass|less|stylus-loader之前。
                    "sass-loader" // 将 Sass 编译成 CSS,默认使用 Node Sass
                ]
            }]
        }
    };
    

    还可以给loader加一些配置项:

    module.exports = {
        ...
        module: {
            rules: [{
                test: /\.scss$/,
                use: [
                    'style-loader', 
                    {
                        loader: 'css-loader',
                        options:{
                            importLoaders:2 ,//如果sass文件里还引入了另外一个sass文件,另一个文件还会从sass-loader向上解析。如果不加,就直接从css-loader开始解析// 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader
                            modules: true //开启css的模块打包。css样式不会和其他模块发生耦合和冲突
                        }
                    }, 
                    'postcss-loader',
                    'sass-loader', 
                ]
            }]
        }
    };
    
    • 为字体图标文件配loader:
      阿里巴巴矢量图标库中,把需要的字体图标下载到本地,解压。将iconfont.eot iconfont.svg iconfont.ttf iconfont.woff 文件放入到项目中,在src中新建一个放字体图标的文件夹font。将iconfont.css文件拷贝到项目中,自己改一下引入字体图标的路径。

    需要安装 file-loader:

    npm i file-loader -D
    

    webpack.config.js

    module.exports = {
        module: {
            rules: [{
                test: /\.(eot|ttf|svg|woff)$/,
                use:{
                    loader:'file-loader'
                }
            }]
        }
    };
    

    详细请看官方文档:asset-management

    2.2 plugin
    • plugin : 可以在webpack运行到某个时刻的时候,帮你做一些事情
      使用plugins让打包更便捷
      HtmlWebpackPlugin :htmlWebpackPlugin 会在打包结束后,自动生成一个html文件,并把打包生成的js自动引入到这个html文件中
      需要安装html-webpack-plugin
    npm i html-webpack-plugin -D
    

    webpack.config.js

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const path = require('path');
    
    module.exports = {
      entry: './src/index.js',
      output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'main.js'
      },
        plugins: [new HtmlWebpackPlugin({
            template: './src/index.html' //以index.html为模板,把打包生成的js自动引入到这个html文件中
        })]
    };
    

    CleanWebpackPlugin :自动清除上一次打包的dist文件
    需要安装clean-webpack-plugin

    npm i clean-webpack-plugin -D
    

    webpack.config.js

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    const path = require('path');
    
    module.exports = {
      entry: 'index.js',
      output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'index_bundle.js'
      },
        plugins: [
            new HtmlWebpackPlugin({
            template: 'src/index.html' //在打包之后,以.html为模板,把打包生成的js自动引入到这个html文件中
        }),
            new CleanWebpackPlugin(['dist']), // 在打包之前,可以删除dist文件夹下的所有内容
        
        ]
    };
    
    2.3 Entry与Output
    • Entry与Output的基础配置
      在打包多入口文件时的配置

    基本用法:在 webpack.config.js 中:

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    const path = require('path');
    
    module.exports = {
      entry: {
        main: './src/index.js',
        sub: './src/index.js'
      },
      output: {
        publicPath: 'http://cdn.com.cn', //将注入到html中的js文件前面加上地址
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
      },
        plugins: [
            new HtmlWebpackPlugin({
            template: './src/index.html' //在打包之后,以index.html为模板,把打包生成的js自动引入到这个html文件中
        }),
            new CleanWebpackPlugin(), // 在打包之前,可以删除dist文件夹下的所有内容
        ]
    };
    

    详细请看官网:Output output-management

    2.4 SourceMap 的配置

    sourcemap:打包编译后的文件和源文件的映射关系,用于开发者调试用。

    • source-map 把映射文件生成到单独的文件,最完整但最慢
    • cheap-module-source-map 在一个单独的文件中产生一个不带列映射的Map
    • eval-source-map 使用eval打包源文件模块,在同一个文件中生成完整sourcemap
    • cheap-module-eval-source-map sourcemap和打包后的JS同行显示,没有映射列

    development环境推荐使用:devtool: 'cheap-module-eval-source-map'
    production环境推荐使用: devtool: 'cheap-module-source-map',

    webpack.config.js

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    
    module.exports = {
        mode: 'development',
        devtool: 'cheap-module-eval-source-map',
        //devtool:'none',//在开发者模式下,默认开启sourcemap,将其关闭
        //devtool:'source-map'//开启映射打包会变慢
        //devtool:'inline-source-map'//不单独生成.map文件,会将生成的映射文件以base64的形式插入到打包后的js文件的底部
        //devtool:'cheap-inline-source-map'//代码出错提示不用精确显示第几行的第几个字符出错,只显示第几行出错,会提高一些性能
        //devtool:'cheap-module-inline-source-map'//不仅管自己的业务代码出错,也管第三方模块和loader的一些报错
        //devtool:'eval'//执行效率最快,性能最好,但是针对比较复杂的代码的情况下,提示内容不全面
        //devtool: 'cheap-module-eval-source-map',//在开发环境推荐使用,提示比较全,打包速度比较快
        //devtool: 'cheap-module-source-map',//在生产环境中推荐使用,提示效果会好一些
    }
    

    详细请看官网:devtool

    2.5 使用WebpackDevServer 提升开发效率

    解决每次在src里编写完代码都需要手动重新运行 npm run dev

    1. 在 package.json 中配置
    {
      "name": "Frank",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "webpack",
        "watch": "webpack --watch",// 加--watch自动监听代码的变化
      },
    }
    
    1. 在 webpack.config.js 中,加 devServer
      安装 npm i webpack-dev-server –D
    • contentBase :配置开发服务运行时的文件根目录
    • open :自动打开浏览器
    • host:开发服务器监听的主机地址
    • compress :开发服务器是否启动gzip等压缩
    • port:开发服务器监听的端口

    webpack.config.js

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    
    module.exports = {
        mode: 'development',
        devtool: 'cheap-module-eval-source-map',
        entry: {
            main: './src/index.js'
        },
    +   devServer: {
            contentBase: './dist',
            open: true,
            port: 8080,
            proxy: {//配置跨域,访问的域名会被代理到本地的3000端口
                '/api': 'http://localhost:3000'
            }
        },
        module: {
            rules: []
        },
        plugins: [],
        output: {
            filename: '[name].js',
            path: path.resolve(__dirname, 'dist')
        }
    }
    

    在 package.json 中:

    {
      "name": "Frank",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "webpack",
        "watch": "webpack --watch",// 加--watch自动监听代码的变化
        "start": "webpack-dev-server",//配置热更新
      },
    }
    

    详细请看官网 :dev-server

    1. 扩充知识:自己写一个类似webpackdevserver的工具
      在 package.json 中:
    {
      "name": "Frank",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "webpack",
        "watch": "webpack --watch",// 加--watch自动监听代码的变化
        "start": "webpack-dev-server",//配置热更新
        "server" : "node server.js" //自己写一个类似webpackdevserver的工具
      }
    }
    

    安装 :npm i express webpack-dev-middleware -D

    在 项目根目录下创建 server.js 文件

    在 server.js 中:

    const express = require('express');
    const webpack = require('webpack');
    const webpackDevMiddleware = require('webpack-dev-middleware');
    const config = require('./webpack.config.js');
    const complier = webpack(config);
    
    const app = express();
    
    app.use(webpackDevMiddleware(complier, {}));
    
    app.listen(3000, () => {
        console.log('server is running');
    });
    
    2.6 模块热替换(hot module replacement)

    在 package.json 中:

    {
      "name": "Frank",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "webpack-dev-server" //将文件打包到内存中,有助于开发
      }
    }
    

    在 webpack.config.js 中

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    const webpack = require('webpack');
    
    module.exports = {
        mode: 'development',
        devtool: 'cheap-module-eval-source-map',
        entry: {
            main: './src/index.js'
        },
        devServer: {
            contentBase: './dist',
            open: true,
            port: 8080,
            hot: true,//开启热更新
            hotOnly: true//尽管HMR(热模块替换)功能没有实现,也不让浏览器刷新
        },
        module: {
            rules: [{
                test: /\.(jpg|png|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        name: '[name]_[hash].[ext]',
                        outputPath: 'images/',
                        limit: 10240
                    }
                } 
            }, {
                test: /\.(eot|ttf|svg)$/,
                use: {
                    loader: 'file-loader'
                } 
            }, {
                test: /\.scss$/,
                use: [
                    'style-loader', 
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 2
                        }
                    },
                    'postcss-loader',
                    'sass-loader',
                ]
            }, {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'postcss-loader'
                ]
            }]
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: 'src/index.html'
            }), 
            new CleanWebpackPlugin(['dist']),
            new webpack.HotModuleReplacementPlugin() //使用模块热更新插件
        ],
        output: {
            filename: '[name].js',
            path: path.resolve(__dirname, 'dist')
        }
    }
    

    index.js

    //如果模块启用了HMR,就可以用 module.hot.accept(),监听模块的更新。
    if (module.hot) {
      module.hot.accept('./library.js', function() {
        // 移除老模块
        // 添加新模块
      })
    }
    

    注意点:

    引入css,用框架Vue,React 时,不需要写 module.hot.accept(),因为在使用css-loader,vue-loader,babel-preset时,就已经配置好了HMR,不需要自己写

    详细请看官方文档:hot-module-replacement api/hot-module-replacement concepts/hot-module-replacement

    2.7 使用 Babel 处理 ES6/7 语法 转义为ES5

    BABEL官网:https://babeljs.io/setup
    安装依赖包:

    npm i babel-loader @babel/core @babel/preset-env -D
    //生产依赖,兼容低版本浏览器
    npm install --save @babel/polyfill
    

    在 webpack.config.js 中

    module: {
      rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,//不需要对第三方模块进行转换,耗费性能
            loader: "babel-loader" ,
            options:{
                "presets": [["@babel/preset-env",{
                    targets: {//这个项目运行在大于什么版本的浏览器上,已经支持es6的语法的高版本浏览器就不需要转义成es5了
                        edge: "17",
                        firefox: "60",
                        chrome: "67",
                        safari: "11.1",
                      },
                    useBuiltIns:'usage' //按需添加polyfill,把用到的代码都转成低版本浏览器兼容的
                }]]
            }
        }
      ]
    }
    

    在 index.js 中:

    //在业务代码运行之前最顶部导入
    import "@babel/polyfill";
    

    注意:在开发类库,第三方模块或组件库时不能用 @babel/polyfill 这种方案,因为会把声明的变量变成全局变量,会污染全局环境。
    安装:

    npm install --save-dev @babel/plugin-transform-runtime
    npm install --save @babel/runtime
    npm install --save @babel/runtime-corejs2
    

    在 webpack.config.js 中

    module: {
      rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,//不需要对第三方模块进行转换,耗费性能
            loader: "babel-loader" ,
            options:{
                "plugins": [["@babel/plugin-transform-runtime",{
                    "corejs": 2,
                    "helpers": true,
                    "regenerator": true,
                    "useESModules": false
                }]]
            }
        }
      ]
    }
    

    由于babel需要配置的内容非常多,我们需要在项目根目录下创建一个 .babelrc 文件。

    就不需要在 webpack.config.js 中写 babel 的配置了。

    在 .babelrc 中:

    {
      "plugins": [["@babel/plugin-transform-runtime",{
          "corejs": 2,
          "helpers": true,
          "regenerator": true,
          "useESModules": false
      }]]
    }
    
    2.8 配置 React 代码的打包

    业务代码:

    在 .babelrc 中:

    { 
                "presets": [
                    ["@babel/preset-env",{
                    targets: {
                        edge: "17",
                        firefox: "60",
                        chrome: "67",
                        safari: "11.1",
                      },
                    useBuiltIns:'usage' 
                        }
                    ],
                    "@babel/preset-react"
                ]
            }
    //执行顺序:从下往上,从右向左的顺序
    

    安装:

    npm i react react-dom --save
    npm install --save-dev @babel/preset-react
    

    详细内容请看官网:babel-loader

    相关文章

      网友评论

          本文标题:Webpack核心概念(二)

          本文链接:https://www.haomeiwen.com/subject/lpnytctx.html