8.6 Webpack

1. webpack

  • 模块打包机css

    分析项目结构,找到JavaScript模块以及其它 的一些浏览器不能直接运行的拓展语言(Scss,TypeScript等),并将其转换和打包为合适的格式供浏览器使用html

2. 本地安装webpack webpack-cli

1. 初始化npm

  • 建立文件夹(webpack)
  • 初始化
npm init //建立package.json
复制代码

2. 本地安装

  • 指定文件夹下安装
npm install  webpack -D
    npm install  webpack-cli -D
复制代码

3. webpack文件夹

  • webpack文件夹下新建src(初始)和dist(打包)文件夹
  • 新建index.js和index.html
  • webpack文件夹下新建webpack.config.js并进行如下配置
const path = require('path');//导入path模块
    module.exports = {
        //设置开发环境
        mode: 'development',//development开发环境production上线环境
        entry:{//入口文件
            index: './src/index.js'
        },
        output:{//出口文件
            //当前绝对路径
            path: path.resolve(__dirname,'dist'),
            filename:'[name].js',//与入口文件同名
        }
    }
复制代码
  • pacjage.json进行如下配置
"scripts": {
        "build": "webpack"
      },
复制代码

3. 服务与热更新

1. webpack.config.js

//配置webpack开发服务功能 服务与热更新配置
    devServer: {
        //设置基本目录功能
        contentBase: path.resolve(__dirname,'dist'),
        //服务器ip,可使用localhost
        host: 'localhost',
        //配置服务端口号
        port: 8088,
        //服务压缩是否开启
        compress: true
    },
复制代码

2. webpack-dev-server

  • 安装webpack-dev-server
npm install webpack-dev-server -D
复制代码
  • package.json
"scripts": {
        "dev": "webpack-dev-server"
    },
复制代码
  • webpack.config.js
//配置webpack开发服务功能
    devServer: {
        //自动打开浏览器
        open: true
    },
复制代码

4. HTML文件打包

1. 单文件

  • 安装html-webpack-plugin
npm install html-webpack-plugin -D
复制代码
  • webpack.config.js
const HtmlPlugin = require('html-webpack-plugin');
    
    plugins: [
            new HtmlPlugin({
                //编译后文件名称
                filename: 'test.html',
                //页面标题
                title: '标题',
                //引入的入口文件
                chunks: ['index'],
                minifiy:{
                    removeAttributeQuotes:true
                    //对html文件进行压缩,去掉属性的双引号
                },
                hash:true,
                template: './src/index.html'
            })
        ]
复制代码

2. 多页面打包

plugins: [
        new HtmlPlugin({
            //编译后文件名称
            filename: 'test.html',
            //页面标题
            title: '标题',
            //引入的入口文件
            chunks: ['index'],
            minifiy:{
                removeAttributeQuotes:true
                //对html文件进行压缩,去掉属性的双引号
            },
            hash:true,
            template: './src/index.html'
        }),
         new HtmlPlugin({
            filename: 'test2.html',
            title: '标题2',
            chunks: ['index2'],
            minifiy:{
                removeAttributeQuotes:true
            },
            hash:true,
            template: './src/index2.html'
        })
    ]

复制代码

3. HTML中的图片打包

  • 安装html-withimg-loader
npm install html-withimg-loader -D
复制代码
  • webpack.config.js
module:{
        rules: [
            {
                test: /\.(html|htm)$/i,
                loader: 'html-withimg-loader'
            }
        ]
    }
复制代码

5. js代码压缩(目前不须要使用)

  • 安装 uglifyjs-webpack-plugin
npm install uglifyjs-webpack-plugin -D
复制代码
  • webpack.config.js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
    plugins:[
        new UglifyJsPlugin()
    ]
复制代码
  • 基本配置
module.exports = {
        //设置开发环境
        mode: 'production',//development开发环境production上线环境
    },
复制代码

6. css文件打包与分离

1. 打包

  • 入口js文件
import './index.css';
复制代码
  • 安装style-loader css-loader
npm install style-loader -D
    npm install css-loader -D
复制代码
  • webpack.config.js
module:{
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader','css-loader']
            }
        ]
    }
复制代码

2. css分离

  • 安装extract-text-webpack-plugin
npm install extract-text-webpack-plugin@next -D
    //next表示下一个版本
复制代码
  • webpack.config.js
const ExtractTestPlugin = require('extract-text-webpack-plugin');
    
    plugins: [
        new ExtractTestPlugin('css/index.css')
    ]
        
    module:{
        rules: [
            {
                test: /\.css$/,
                use: ExtractTestPlugin.extract({
                    fallback: 'style-loader',
                    use: "css-loader"
                })
            }
        ]
    }
复制代码

3. CSS中引用 图片

  • 安装file-loader url-loader
npm install file-loader url-loader -D
复制代码
  • webpack.config.js
module:{
        rules: [
            {
                test: /\.(png|jpg|jpeg|gif)/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 500,
                        //是把小于500B的文件打成Base64的格式,写入css
                        outputPath:'images/'
                    }
                }]
            }
        ]
    }
复制代码

4. 路径问题

  • 但若是图片不是base64而是一个图片文件,这时候就会出现路径问题
  • webpack.config.js
module.exports = {
        output:{
            publicPath: 'http://localhost:8088/'
        }
    }
复制代码

7. sass打包和分离

1. 打包

  • 安装node-sass sass-loader
npm install  node-sass sass-loader -D
复制代码
  • 入口js导入scss
import './common.scss';
复制代码
  • webpack.config.js
  • css打包到js中
module:{
        rules: [
            {
                test: /\.scss$/,
                use: ['style-loader','css-loader','sass-loader']
            }
        ]
    }
复制代码

2. 分离

module:{
        rules: [
            {
                test: /\.scss$/,
                use: ExtractTestPlugin.extract({
                    fallback: 'style-loader',
                    use: ["css-loader","sass-loader"]
                })
            }
        ]
    }
复制代码

8. CSS3前缀

  • 安装:postcss-loader autoprefixer
npm install postcss-loader autoprefixer -D
复制代码
  • 新建文件:postcss.config.js
module.exports = {
        plugins: [
            require('autoprefixer')({
                "browsers":[
                    "defaults",
                    "not ie<11",
                    "last 2 versions",
                    ">1%",
                    "iOS 7",
                    "last 3 iOS versions"
                ]
            })
        ]
    };
复制代码
  • webpack.config.js
module:{
        rules: [
            {
                test: /\.css$/,
                use: ExtractTestPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders:  1
                            }
                        },
                        'postcss-loader'
                    ]
                })
            }
        ]
    }
复制代码

9. 清除未使用的css

  • 安装purifycss-webpack purify-cs
npm install purifycss-webpack purify-css -D
复制代码
  • webpack.config.js
const glob = require('glob');
    const PurifyCSSPlugin = require('purifycss-webpack');
    
    module.exports = {
        plugins: [
            new PurifyCSSPlugin({
            paths: glob.sync(path.join(__dirname,'src/*.html'))
            })
        ]
    };
复制代码

10. babel

  • 安装babel-core babel-loader @babel/core @babel/preset-env
npm install babel-core babel-loader @babel/core @babel/preset-env -D
复制代码
  • webpack.config.js
module:{
            rules: [
                {
                    test:/\.js$/,
                    use:[
                        {
                            loader:'babel-loader',
                            options:{
                                presets:['@babel/preset-env']
                            }
                        }
                    ],
                    exclude:/node_modules/
                }
            ]
        }
复制代码

11. 打包注释

  • webpack.config.js
const webpack = require('webpack');
    module.exports = {
        plugins: [
            new webpack.BannerPlugin('不要抄袭!!!'),
        ]
    };
复制代码

12. 开发环境与生产环境

  • devDependencies 存放测试代码依赖的包或构建工具的包
  • dependencies 存放项目或组件代码中依赖到的
  • 安装所有项目依赖包:npm install
  • 安装生产环境依赖包:npm install --production
  • npm install jquery --save

13. 打包第三方类库

  • 安装jquery
npm install --save jquery
复制代码
  • webpack.config.js
const webpack = require('webpack');
    module.exports = {
        plugins: [
            new webpack.ProvidePlugin({
                $:'jquery'
            })
        ]
    };
复制代码

14. 资源拷贝

  • 安装 copy-webpack-plugin
npm install copy-webpack-plugin -D
复制代码
  • webpack.config.js
var copyWebpackPlugin = require('copy-webpack-plugin');
    module.exports = {
        plugins: [
            new copyWebpackPlugin([
                {
                    from: __dirname + '/src/public',
                    to:'./public'
                }
            ])
        ]
    };
复制代码

15. 模块化配置

  • 新建entry_webpack.js
const entry = require("./webpack/entry_webpack.js");
    const entry = {
        entry:'./src/entry.js'
    };
    module.exports = entry;
复制代码
  • webpack.config.js
module.exports = {
        entry: entry,
    }
复制代码
相关文章
相关标签/搜索