美文网首页webpackVue
webpack成神之路(二)

webpack成神之路(二)

作者: AAA前端 | 来源:发表于2019-05-11 10:43 被阅读26次
  1. 现在webpack每次要手动引入js到index.html中,体验很不好。安装插件html-webpack-plugin. 插件用法可以到https://www.npmjs.com/查阅
cnpm i --save-dev html-webpack-plugin
  • 在webpack中配置

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

module.exports = {
    mode: 'production', //开发模式 development  生产模式production
    entry: './src/index.js', // 入口
    output:{
        filename: "index.[hash:8].js",      // 打包后的文件名,带上8位数的hash值
        path: path.resolve(__dirname, 'build')   // 打包后的绝对路径 path自带模块相对路径转换绝对路径
    },
    devServer:{
        port: 1234, // 端口号    不能6666-6669 ,安全限制在chrome中不能成功
        progress: true, // 加上进度条
        contentBase: './', //静态服务的目录。默认当前根目录,如果index.html在src下,这里就要改为./src
        open: true, //自动打开页面
        compress: true, //压缩
    },
    plugins:[   //插件列表
        new HtmlWebpackPlugin({
            template: './index.html',  // 模板
            filename: 'index.html', //打包后的文件名
            minify:{    // 更多配置 https://github.com/kangax/html-minifier#options-quick-reference
                removeAttributeQuotes: true ,// 删除双引号
                collapseWhitespace: true, // 折叠为一行
            },
            hash: true, //在js后面添加hash,防止缓存
        })
    ]
}
  • 命令行运行npm run build可以看到打包后自动生成了index.html.
    image.png
  1. 现在配置解析css文件 处理css 首先加安装模块 style-loader, css-loader style-loader是把css加载到index.html中,css-loader是处理css中引入其他css文件的loader;
    image.png
  • 配置webpack.config.js

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

module.exports = {
    mode: 'development', //开发模式 development  生产模式production
    entry: './src/index.js', // 入口
    output:{
        filename: "index.[hash:8].js",      // 打包后的文件名,带上8位数的hash值
        path: path.resolve(__dirname, 'build')   // 打包后的绝对路径 path自带模块相对路径转换绝对路径
    },
    devServer:{
        port: 1234, // 端口号    不能6666-6669 ,安全限制在chrome中不能成功
        progress: true, // 加上进度条
        contentBase: './', //静态服务的目录。默认当前根目录,如果index.html在src下,这里就要改为./src
        open: true, //自动打开页面
        compress: true, //压缩
    },
    plugins:[   //插件列表
        new HtmlWebpackPlugin({
            template: './index.html',  // 模板
            filename: 'index.html', //打包后的文件名
            minify:{    // 更多配置 https://github.com/kangax/html-minifier#options-quick-reference
                removeAttributeQuotes: true ,// 删除双引号
                collapseWhitespace: true, // 折叠为一行
            },
            hash: true, //在js后面添加hash,防止缓存
        })
    ],
    module:{ // 模块
        rules:[
            {
                test: /\.css$/,
                // use 可以是字符串 数组
                //  style-loader 把css 插入到html中
                // css-loader 处理 @import 其他css的
                // 处理顺序是从后往前处理的
                use:['style-loader', 'css-loader']
            }
           
        ]
    }
}
  • 在src下创建文件夹css 。里面创建index.css a.css 分别设置body北京颜色,在index.js中引入index.css.


    image.png
  • 命令行运行npm run serve。启动服务


    image.png
  1. 当然我们也可以用less sass stylus. 这里用less示范一下。
  • 安装less less-loader


    image.png
  • webpack.config.js配置,less-loader放后面,先处理成css。之后再嵌入到html中
image.png
  • src下创建less文件夹,创建index.less文件。并写入样式。在index.js中引入


    image.png
  • 页面效果


    image.png
  1. 但是这里有个问题,如果我们自己在html中设置body背景色,会被index.js中引入的css样式所覆盖,(require的css在自己写的style之下)


    image.png
    image.png

*我们可以在webpack.config.js中配置 style-loader


image.png
image.png
  • 现在完美解决了
  1. 抽离css出来
  • 命令行安装 cnpm i --save-dev mini-css-extract-plugin
  • 配置webpack.config.js

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

module.exports = {
    mode: 'development', 
    entry: './src/index.js', 
    output: {
        filename: "index.[hash:8].js",
        path: path.resolve(__dirname, 'build')  
    },
    devServer: {
        port: 1234, 
        contentBase: './', 
    },
    plugins: [  
        new HtmlWebpackPlugin({
            template: './index.html',  
            filename: 'index.html', 
            minify: {  
                removeAttributeQuotes: true,
                collapseWhitespace: true, 
            },
            hash: true, 
        }),
        new MiniCssExtractPlugin({
            filename: '[name].css',  // css名
            chunkFilename: '[id].css',
          }),
    ],
    module: { // 模块
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader']  //MiniCssExtractPlugin.loader替换  style-loader 
            },
            {
                test: /\.less$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
            }

        ]
    }
}
image.png

*css被单独抽离出来了

  1. 现在css有些样式没有加上浏览器前缀,比如rotate。现在需要安装cnpm i --save-dev autoprefixer cssnano postcss-cssnext (autoprefixer 自动添加前缀,cssnano 压缩css代码,postcss-cssnext css的下一代,使用css4的新语法等等)
  • webpack.config.js 中在css-loader之前使用postcss-loader


    image.png
  • 然后postcss-loader 需要一个配置文件postcss.config.js


    image.png
  • 在index.less文件中

body{
    p{
        color: #666;
        font-size: 30px;
        background-color: aqua;
        transform: rotate(30deg);
    }
}
  • 启动服务,控制台可以看到签注添加成功了。


    image.png
  • 或者也可以把postcss-loader的配置全部放到postcss.config.js中。

image.png
  • 启动服务一样可以达到这个效果
  1. 还有另一种压缩css的方法,可以看 mini-css-extract-plugin 插件使用中有说明https://www.npmjs.com/package/mini-css-extract-plugin
image.png
  • 安装官方说明,安装 cnpm i terser-webpack-plugin optimize-css-assets-webpack-plugin --save-dev

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

module.exports = {
    mode: 'development', 
    entry: './src/index.js', 
    output: {
        filename: "index.[hash:8].js",
        path: path.resolve(__dirname, 'build')  
    },
    devServer: {
        port: 1234, 
        contentBase: './', 
    },
    plugins: [  
        new HtmlWebpackPlugin({
            template: './index.html',  
            filename: 'index.html', 
            minify: {  
                removeAttributeQuotes: true,
                collapseWhitespace: true, 
            }
        }),
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css',
          }),
    ],
    optimization: {
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
      },
    module: { // 模块
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader','postcss-loader'] 
            },
            {
                test: /\.less$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader','postcss-loader', 'less-loader']
            }

        ]
    }
}
  • 安装之后打包,可以看到css被压缩了。


    image.png
  • 但是 官方有说 设置optimization.minimizer会覆盖webpack提供的默认值

  • 压缩js,安装 cnpm i uglifyjs-webpack-plugin --save-dev

  • webpack.config.js 配置

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
    optimization: {
        minimizer: [new UglifyJsPlugin(
            {
                cache: true,  // 启用cache缓存
                parallel: true, // 并发打包
                sourceMap: true, // 映射原代码地址
              }
        ), new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    },
image.png
  • 打包之后 js也压缩了。
  1. 现在还有点,每次打包前要自己手动删除build文件夹,不然里面有前面打包生成的js.我们想每次打包前自动删除build文件夹。安装cnpm install --save-dev clean-webpack-plugin
  • webpack.config.js
const CleanWebpackPlugin = require('clean-webpack-plugin');
plugins: [
        new CleanWebpackPlugin(),
    ]
  • 现在每次npm run build的时候就会删除build文件夹,再重新打包了。

粘贴一下 目前代码;

webpack.config.js


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    mode: 'production', 
    optimization: {
        minimizer: [new UglifyJsPlugin(
            {
                cache: true,  // 启用cache缓存
                parallel: true, // 并发打包
                sourceMap: true, // 映射原代码地址
              }
        ), new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    },
    entry: './src/index.js', 
    output: {
        filename: "index.[hash:8].js",
        path: path.resolve(__dirname, 'build')  
    },
    devServer: {
        port: 1234, 
        contentBase: './', 
    },
    plugins: [  
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: './index.html',  
            filename: 'index.html', 
            minify: {  
                removeAttributeQuotes: true,
                collapseWhitespace: true, 
            }
        }),
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css',
          }),
    ],
    module: { // 模块
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader','postcss-loader'] 
            },
            {
                test: /\.less$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader','postcss-loader', 'less-loader']
            }

        ]
    }
}

postcss.config.js

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

相关文章

  • webpack成神之路(二)

    现在webpack每次要手动引入js到index.html中,体验很不好。安装插件html-webpack-plu...

  • webpack4.x入门指南(单页面入口)

    webpack 中文文档webpack4.x入门配置Webpack 4.x 小白成神之路 1、安装 webpack...

  • webpack成神之路(七)

    接下来说一下resolve, webpack在查找时会先在当前目录查找,找不到往上一层继续找,再找不到继续往上。。...

  • webpack成神之路(五)

    现在我们试一下多页面配置 我们在src下建立两个js。分别为index.js ,a.js 里面只console.l...

  • webpack成神之路(六)

    现在我们来说一下访问接口的问题,处理跨越问题。 我们想启动一个服务。监听/user接口;server.js 然后我...

  • webpack成神之路(四)

    现在我们有些基层模块依赖于一些全局变量,比如jquery.我们开始怎么设置全局变量.以jquery为例; 首先我们...

  • webpack成神之路(三)

    现在我们来处理js模块,比如es6语法转换为es5语法。这里就需要babel-loader模块了。https://...

  • webpack成神之路(一)

    webpack是干什么的网上一堆,就不赘述了。现在从零开始学习webpack; 初始化项目 安装webpack w...

  • webpack成神之路(十)

    1.公共模块的抽离(单页面没有必要,一般是多页面的)我们在src下创建四个js。分别是a.js,b.js,inde...

  • webpack成神之路(八)

    现在我们继续来说一下配置 noParse;noparse 对于不引用其他的包的库,我们在打包的时候就没有必要去解析...

网友评论

    本文标题:webpack成神之路(二)

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