Webpack 4x 之路 ( 五 )

在上一篇中咱們在html文件中也引用了一張圖片,打包完畢後在瀏覽器控制檯報錯:javascript

GET file:///D:/myweb/webpack/webpack_study_demo/webpack_new_test/dist/src/asserts/login1.png net::ERR_FILE_NOT_FOUND
// 意思是圖片沒找到,下面咱們就來學習怎麼處理HTML中的圖片路徑問題了
處理HTML中的圖片路徑問題

webpack處理資源無往不利,但有個問題老是很苦惱,html中直接使用img標籤src加載圖片的話,由於沒有被依賴,圖片將不會被打包。這個loader解決這個問題,圖片會被打包,並且路徑也處理穩當。額外提供html的include子頁面功能。css

安裝html

$ cnpm install html-withimg-loader --save

html-withimg-loader前端

// webpack.config.js
// 而後在生產環境下增長下列代碼
config.module.rules.push(
    {
      test: /\.(htm|html)$/i,
      loader: 'html-withimg-loader'
    }
  )
$ npm run build
// 而後你就會發現上面的那個問題獲得瞭解決,圖片成功顯示,被轉爲了base64格式寫入了

css進階: less文件的打包與處理

安裝less服務java

$ cnpm install less less-loader --save-dev
// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpack = require('webpack')
const isDev = process.env.NODE_ENV === 'development'
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 分離css
const uglify = require('uglifyjs-webpack-plugin');// js代碼壓縮插件

const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(jpg|png|svg|gif|jpeg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit:500000,
              name: 'images/[name]-[hash].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: 'body'
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
}

if (isDev) {
  // 開發環境下
  config.devServer = {
    host: 'localhost',    // 服務器的IP地址,可使用IP也可使用localhost
    compress: true,    // 服務端壓縮是否開啓
    port: 3000, // 端口
    hot: true,
    open: true
  }

  config.module.rules.push(
    {
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },
    {                                // 【1】 在開發模式下處理,這裏使用的依舊是style-loader
      test: /\.less$/,
      use: ['style-loader', 'css-loader', 'less-loader'] 
    }
  )
} else {
  // 生產模式下
  config.plugins.push(new uglify())
  config.plugins.push(
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  )

  config.module.rules.push(
    {
      test: /\.css$/,
      use: [ MiniCssExtractPlugin.loader, 'css-loader']
    },
    {
      test: /\.less$/,                    //【2】 在生產模式下,這裏實現了less的分離
      use: [ MiniCssExtractPlugin.loader, 'css-loader','less-loader']
    }
  )
  config.module.rules.push(
    {
      test: /\.(htm|html)$/i,
      loader: 'html-withimg-loader'
    }
  )
}

module.exports = config;
$ npm run build
// 打包成功

css進階 : SASS打包與處理

安裝node

$ cnpm install sass --save-dev

這裏須要 在項目目錄下用npm安裝兩個包。node-sasssass-loader
由於sass-loader依賴於node-sass,因此須要先安裝node-sasswebpack

$ cnpm install sass-loader --save-dev
$ cnpm install node-sass@4.5.3 --save-dev
// sass.scss
$nav-color: #FFF;
#nav {
  $width: 100%;
  width: $width;
  height:30px;
  background-color: $nav-color;
}
// 與上面處理less是同樣的作法
// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpack = require('webpack')
const isDev = process.env.NODE_ENV === 'development'
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 分離css
const uglify = require('uglifyjs-webpack-plugin');// js代碼壓縮插件

const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(jpg|png|svg|gif|jpeg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit:500000,
              name: 'images/[name]-[hash].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: 'body'
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
}

if (isDev) {
  // 開發環境下
  config.devServer = {
    host: 'localhost',    // 服務器的IP地址,可使用IP也可使用localhost
    compress: true,    // 服務端壓縮是否開啓
    port: 3000, // 端口
    hot: true,
    open: true
  }

  config.module.rules.push(
    {
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },
    {
      test: /\.less$/,
      use: ['style-loader', 'css-loader', 'less-loader'] 
    },
    {
      test: /\.scss$/,             // 【1】 
      use: ['style-loader', 'css-loader', 'sass-loader']
    }
  )
} else {
  // 生產模式下
  config.plugins.push(new uglify())
  config.plugins.push(
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  )

  config.module.rules.push(
    {
      test: /\.css$/,
      use: [ MiniCssExtractPlugin.loader, 'css-loader']
    },
    {
      test: /\.less$/,
      use: [ MiniCssExtractPlugin.loader, 'css-loader','less-loader']
    },
    {
      test: /\.scss$/,            // 【2】
      use: [ MiniCssExtractPlugin.loader, 'css-loader','sass-loader']
    }
  )
  config.module.rules.push(
    {
      test: /\.(htm|html)$/i,
      loader: 'html-withimg-loader'
    }
  )
}

module.exports = config;
// $ npm run build
// 沒問題

處理css前綴

CSS3已經成了前端的必會技能,可是你必定爲那些屬性須要加前綴,以知足不一樣瀏覽器的兼容,這節課咱們就學習一下如何經過postcss-loadercss3屬性自動添加前綴。css3

爲了瀏覽器的兼容性,有時候咱們必須加入-webkit,-ms,-o,-moz這些前綴。目的就是讓咱們寫的頁面在每一個瀏覽器中均可以順利運行。web

postcss就是一個css的處理器,它有一項很是好的功能就是能夠爲css添加前綴,這將會使得咱們的開發變得很是快速npm

安裝

$  cnpm install --save-dev postcss-loader autoprefixer
// 以及其餘插件
$  cnpm install postcss-import --save-dev
$  cnpm install postcss-cssnext --save-dev //一個模塊化的縮小器,創建在PostCSS生態系統之上。看到的代碼壓縮間距就是這個插件的效果
// 樣式編寫,在每個樣式文件中都加這個
div{
    display: flex;
}
// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpack = require('webpack')
const isDev = process.env.NODE_ENV === 'development'
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 分離css
const uglify = require('uglifyjs-webpack-plugin');// js代碼壓縮插件

const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(jpg|png|svg|gif|jpeg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 500000,
              name: 'images/[name]-[hash].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: 'body'
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
}

if (isDev) {
  // 開發環境下
  config.devServer = {
    host: 'localhost',    // 服務器的IP地址,可使用IP也可使用localhost
    compress: true,    // 服務端壓縮是否開啓
    port: 3000, // 端口
    hot: true,
    open: true
  }

  config.module.rules.push(
    {
      test: /\.css$/,
      use: [
        'style-loader',
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        },
        {
          loader: 'postcss-loader',            // 【1】 加入了postcss-loader
          options: {
            ident: 'postcss',
            plugins: (loader) => [                // 【2】這裏使用了一些插件
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        }

      ]
    },
    {
      test: /\.less$/,
      use: [
        {
          loader: 'style-loader'
        },
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        {
          loader: 'less-loader' // 若是less文件中使用了@import 引入了別的less文件,這裏能夠不用設置importLoaders
        }
      ]
    },
    {
      test: /\.scss$/,
      use: [
        {
          loader: 'style-loader'
        },
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        {
          loader: 'sass-loader'
        }
      ]
    }
  )
} else {
  // 生產模式下
  config.plugins.push(new uglify())
  config.plugins.push(
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  )

  config.module.rules.push(
    {
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: 'postcss-loader',            //【3】在生產模式下的修改,這裏要注意的是位置的放置
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        }
      ]
    },
    {
      test: /\.less$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        'less-loader'
      ]
    },
    {
      test: /\.scss$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        'sass-loader'
      ]
    }
  )
  config.module.rules.push(
    {
      test: /\.(htm|html)$/i,
      loader: 'html-withimg-loader'
    }
  )
}

module.exports = config;

// postcss使用
// 將`postcss-loader`添加到 `webpack.config.js` 中,您能夠單獨的使用它,也能夠是與 `css-loader` 一塊兒使用。在css-loader和style-loader以後使用它,可是在其餘預處理器加載器(如less-loader)以前使用它
$ npm run dev
// 執行後發現前綴添加完畢,而且代碼作了必定的壓縮
使用babel

babel能夠幹什麼呢?

  1. 可讓你使用使用下一代javascript代碼(ES6\ES7),即便這些標準目前尚未被全部瀏覽器所支持
  2. 使用基於javascript進行了擴展的語言,好比Reactjsx;

安裝

$ cnpm install babel-core babel-loader babel-preset-env --save-dev
// 再目錄下創建.babelrc文件
{
    "presets":["env"]
}
// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpack = require('webpack')
const isDev = process.env.NODE_ENV === 'development'
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 分離css
const uglify = require('uglifyjs-webpack-plugin');// js代碼壓縮插件
const glob = require('glob');
const PurifyCSSPlugin = require("purifycss-webpack");


const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(jpg|png|svg|gif|jpeg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 500000,
              name: 'images/[name]-[hash].[ext]'
            }
          }
        ]
      },
      {
        test: /\.js$/,            // 【1】 更改這裏
        use: [
          'babel-loader'
        ],
        exclude: /(node_modules|bower_components)/  // 優化處理加快速度
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: 'body'
    }),
    new webpack.HotModuleReplacementPlugin(),
    new PurifyCSSPlugin({
      // Give paths to parse for rules. These should be absolute!
      paths: glob.sync(path.join(__dirname, 'src/*.html')),
    })
  ]
}

if (isDev) {
  // 開發環境下
  config.devServer = {
    host: 'localhost',    // 服務器的IP地址,可使用IP也可使用localhost
    compress: true,    // 服務端壓縮是否開啓
    port: 3000, // 端口
    hot: true,
    open: true
  }

  config.module.rules.push(
    {
      test: /\.css$/,
      use: [
        'style-loader',
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        }

      ]
    },
    {
      test: /\.less$/,
      use: [
        {
          loader: 'style-loader'
        },
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        {
          loader: 'less-loader' // 若是less文件中使用了@import 引入了別的less文件,這裏能夠不用設置importLoaders
        }
      ]
    },
    {
      test: /\.scss$/,
      use: [
        {
          loader: 'style-loader'
        },
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        {
          loader: 'sass-loader'
        }
      ]
    }
  )
} else {
  // 生產模式下
  config.plugins.push(new uglify())
  config.plugins.push(
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  )

  config.module.rules.push(
    {
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        }
      ]
    },
    {
      test: /\.less$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        'less-loader'
      ]
    },
    {
      test: /\.scss$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: (loader) => [
              require('postcss-import')({ root: loader.resourcePath }),
              require('postcss-cssnext')(),
              require('autoprefixer')(),
              require('cssnano')()
            ]
          }
        },
        'sass-loader'
      ]
    }
  )
  config.module.rules.push(
    {
      test: /\.(htm|html)$/i,
      loader: 'html-withimg-loader'
    }
  )
}

module.exports = config;

測試

// index.js
import './styles/reset.css';
import './styles/index.css';
import './styles/base.less';
import './styles/sass.scss';

{
    let title = 'hello';
    document.getElementById('title').innerHTML = title;
}

// 測試發現沒問題

感謝您的支持!!
相關文章
相關標籤/搜索