webpack4-03-生成html、css3前綴、babel配置等..

目錄結構

lesson-03
   |- build
     |- webpack-config.js   // 配置文件
   |- dist                  // 生成打包結果
   |- node-modules
   |- public                // 靜態資源
     |- index.html          // 模板文件
   |- package.json
   |- package-lock.json
   |- /src
     |- assets
        |- images           
        |- style
     |- index.js
複製代碼

建立html、清除dist目錄文件

  1. 使用 html-webpack-plugin 來建立html頁面,並自動引入打包生成的 js 文件
  2. 使用 clean-webpack-plugin 清除出口目錄的文件
  • 安裝
npm i webpack-html-plugin clean-webpack-plugin -D
複製代碼
  • 配置文件新增 html-webpack-plugin
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')    // +
const CleanWebpackPlugin = require('clean-webpack-plugin') // +

const resolve = (dir) =>  path.resolve(__dirname, dir)
module.exports = {
  mode: 'development',
  entry: resolve('../src/index.js'),
  output: {
    filename: 'bundle.js',
    path: resolve('../dist')
  },
  module: {
    rules: [
      {
        test: /\.(css|scss|sass)$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'sass-loader',
            options: {
              implementation: require('dart-sass')
            }
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      }
    ]
  },
  plugins: [                    // +
    new CleanWebpackPlugin(),   // +
    new HtmlWebpackPlugin({     // +
      title: 'Lesson-03',         // +
      template: resolve('../public/index.html') // +
    })                          // +
  ]                             // +
} 
複製代碼
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
	<div id="box"></div>
</body>
</html>
複製代碼

運行webpackcss

npm run dev


> lesson-02@1.0.0 dev C:\Users\Qin\Desktop\js-demo\webpack4-lesson\lesson-03
> npx webpack --config ./build/webpack.config.js

Hash: fed721cbb72ce9b765de
Version: webpack 4.30.0
Time: 2379ms
Built at: 2019-05-04 09:22:31
     Asset       Size  Chunks             Chunk Names
     F.png  416 bytes          [emitted]
 bundle.js   28.5 KiB    main  [emitted]  main
index.html  205 bytes          [emitted]
Entrypoint main = bundle.js
[./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js?!./src/assets/style/index.scss] ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js??ref--5-2!./src/assets/style/index.scss 334 bytes {main} [built]
[./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js?!./src/assets/style/style.css] ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js??ref--5-2!./src/assets/style/style.css 458 bytes {main} [built]
[./src/assets/images/F.png] 51 bytes {main} [built]
[./src/assets/style/index.scss] 1.25 KiB {main} [built]
[./src/assets/style/style.css] 1.25 KiB {main} [built]
[./src/index.js] 259 bytes {main} [built]
    + 4 hidden modules
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [./node_modules/html-webpack-plugin/lib/loader.js!./public/index.html] 426 bytes {0} [built]
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 878 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 552 bytes {0} [built]
        + 1 hidden module
複製代碼

運行成功後,會在dist文件夾內生成index.htmlhtml

配置自動添加css3前綴

  • 安裝
npm i postcss-loader autoprefixer -D
複製代碼
  • 修改 webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const autoprefixer = require('autoprefixer')  // +

const resolve = (dir) =>  path.resolve(__dirname, dir)
module.exports = {
  mode: 'development',
  entry: resolve('../src/index.js'),
  output: {
    filename: 'bundle.js',
    path: resolve('../dist')
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader'
      },
      {
        test: /\.(css|scss|sass)$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {              // +
              importLoaders: 1      // +
            }                       // +
          },
          {
            loader: 'sass-loader',
            options: {
              implementation: require('dart-sass')
            }
          },
          {
            loader: 'postcss-loader'
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'Lesson-03',
      template: resolve('../public/index.html')
    })
  ]
} 
複製代碼

在根目錄新增 postcss.config.jsnode

module.exports = {
	plugins: {
    autoprefixer: {}
  }
}
複製代碼

修改 index.scsswebpack

body {
	display: flex;
	justify-content: center;
	align-items: center;
	#box {
		background-color: yellow;
		background-repeat: no-repeat;
		transform: translateX(50px);
	}
}
複製代碼

運行webpackcss3

npm run dev
複製代碼

再打開dist/index.html文件時,發現只有 transform 添加了前綴,git

-webkit-transform: translateX(50px);
transform: translateX(50px);
複製代碼

display: flex... 並無添加前綴github

display: flex;
justify-content: center;
align-items: center;
複製代碼

上面的問題,主要緣由是須要配置指定瀏覽器的範圍內添加CSS前綴才能給 display: flex等,添加前綴。web

如今有四種配置方法能夠解決上面的問題。npm

方法一

直接在 webpack.config.js 中配置json

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const autoprefixer = require('autoprefixer')

const resolve = (dir) =>  path.resolve(__dirname, dir)
module.exports = {
  mode: 'development',
  entry: resolve('../src/index.js'),
  output: {
    filename: 'bundle.js',
    path: resolve('../dist')
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader'
      },
      {
        test: /\.(css|scss|sass)$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2
            }
          },
          {
            loader: 'sass-loader',
            options: {
              implementation: require('dart-sass')
            }
          },
          {
            loader: 'postcss-loader',
            options: {                  // +
              plugins: [                // +
                autoprefixer({          // +
                  browsers: [           // +
                    "> 1%",             // +
                    "last 2 version",   // +
                    "not ie <= 8"       // +
                  ]                     // +
                })                      // +
              ]                         // +
            }                           // +
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'Lesson-03',
      template: resolve('../public/index.html')
    })
  ]
} 
複製代碼

方法二

postcss.config.js 中配置

module.exports = {
	plugins: {
        autoprefixer: {
    	    browsers: ['> 1%', 'last 2 version', 'not ie <= 8']    // +
        }
    }
}
複製代碼

方法三

package.json 中配置

{
  "name": "lesson-03",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "npx webpack --config ./build/webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    ...
  },
  "browserslist": [         // +
    "> 1%",                 // +
    "last 2 version",       // +
    "not ie <= 8"           // +
  ]                         // +
}
複製代碼

方法四 (教程最終選擇了此方法)

在跟目錄新增 .browserslistrc 配置文件。

.browserslistrc 內容以下:

> 1%
last 2 versions
not ie <= 8
複製代碼

目錄以下:

lesson-03
   |- /build
   |- /dist                  // 生成打包結果
   |- /node-modules
   |- /public                // 靜態資源
   |- package.json
   |- package-lock.json
   |- /src
   |- .browserslistrc       // +
   |- .gitignore
   |- package.json
   |- postcss.config.js
   |- README.md
複製代碼

四種辦法不能同時出現,不然會報錯,配置其中一種便可。

運行

npm run dev
複製代碼

再打開dist/index.html, 在控制檯查看樣式:

body {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
}
複製代碼

可發現已經成功添加了廠商的前綴,還添加了display:flex低版本瀏覽器的舊版flex樣式。最終獲得咱們想要的效果了!!!!

配置babel,ES6/7/8 轉 ES5 語法

  • 安裝
npm install babel-loader @babel/core @babel/preset-env -D
複製代碼
  • 修改 webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const autoprefixer = require('autoprefixer')

const resolve = (dir) =>  path.resolve(__dirname, dir)
module.exports = {
  mode: 'development',
  entry: resolve('../src/index.js'),
  output: {
    filename: 'bundle.js',
    path: resolve('../dist')
  },
  module: {
    rules: [
      {                         // +
        test: /\.jsx?$/,        // +
        loader: 'babel-loader'  // +
      },                        // +
      {
        test: /\.(css|scss|sass)$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          {
            loader: 'sass-loader',
            options: {
              implementation: require('dart-sass')
            }
          },
          {
            loader: 'postcss-loader'
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'Lesson-03',
      template: resolve('../public/index.html')
    })
  ]
} 
複製代碼
  • 根目錄新增 babel.config.js 文件
module.exports = {
	presets: [
		'@babel/preset-env'
	]
}
複製代碼

運行webpack

npm run dev
複製代碼

能夠看到 ES6語法被轉成了ES5語法了。

到這裏其實尚未完成,只是轉了語法,並無把api轉成ES5。

ES6/7/8 Api 轉ES5

@babel/core、@babel/preset-env 只會將 ES6/7/8語法轉換爲ES5語法,可是對新api並不會轉換。

咱們能夠經過 babel-polyfill 對一些不支持新語法的客戶端提供新語法的實現。

  • 安裝
npm install @babel/polyfill -D
複製代碼
  • 修改 webpack.config.js 配置
  • entry 中添加 @babel-polyfill
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const autoprefixer = require('autoprefixer')

const resolve = (dir) =>  path.resolve(__dirname, dir)
module.exports = {
  mode: 'development',
  entry: {
    app: ['@babel/polyfill', resolve('../src/index.js')]    // +
  },
  output: {
    filename: 'bundle.js',
    path: resolve('../dist')
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader'
      },
      {
        test: /\.(css|scss|sass)$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          {
            loader: 'sass-loader',
            options: {
              implementation: require('dart-sass')
            }
          },
          {
            loader: 'postcss-loader'
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'Lesson-03',
      template: resolve('../public/index.html')
    })
  ]
} 
複製代碼

最後運行webpack

npm run dev
複製代碼

便可查看代碼已成功轉換ES語法、Api !!!

項目地址

源碼地址點擊這GitHub

相關文章
相關標籤/搜索