webpack v4 从dev到prd

目次

  • 概述
  • Big changes
  • 加载loader要领总结
  • 开辟必备的loader&plugins
  • 优化向prd进发
  • 未完待续

概述

本月迎来了 v4 正式版的宣布,本文用于学习新特征和总结开辟必用plugin & loader,从dev到prd,走你~

Big changes

  • Environment

    • Node.js 4 is no longer supported. Source Code was upgraded to a higher ecmascript version.
  • Usage

    • You have to choose (mode or –mode) between two modes now: production or development

本次新版本中引入了 mode 设置项,开辟者可在 none,development(开辟 ) 以及 production(产物)三种形式间挑选。该设置项缺省情况下默许运用 production 形式。

  • development 形式给你极致的开辟体验,包括浏览器调试相干东西,极快的增量编译,雄厚周全的报错信息…
  • production 形式则包括大批发版优化,代码紧缩,丝般光滑的运转时优化,开辟相干代码的消除,易用,etc.
  • none 不运用预设,即是老版本中悉数本身设置的原始状况。

eg:

webpack --mode development
  • Usage

    • Some Plugin options are now validated
    • CLI has been move to webpack-cli, you need to install webpack-cli to use the CLI
    • The ProgressPlugin (–progress) now displays plugin names

At least for plugins migrated to the new plugin system

新版中将 webpack 敕令行东西拆分到零丁的堆栈中,所以须要分外装置 webpack-cli。

npm init -y //初始化项目
npm install webpack webpack-cli -D //装置webpack webpack-cli 依靠
npx webpack --mode development // npx能够直接运转node_modules/.bin目次下面的敕令

或许经由过程设置package.json的script build
"scripts": {
    "build": "webpack --mode development",
},

加载loader要领总结

  • use
module: {
    rules:[
        { 
            test: /\.css$/,
            use: ['style-loader','css-loader']
        }
    ]
}

css-loader用来剖析处置惩罚CSS文件中的url途径,

要把CSS文件变成一个模块
多个loader是有递次请求的,从右往左写,由于转换的时刻是从右往左转换

此插件先用css-loader处置惩罚一下css文件,再用style-loader把CSS文件变成style标签插进去head中

  • loader
module: {
    rules:[
        {
            test: /\.css$/,
            loader: ["style-loader", "css-loader"]
        },
    ]
}
  • use+loader
module: {
    rules:[
        {
            test: /\.css$/,
            use:[
                { loader:"style-loader"},
                { 
                    loader: 'css-loader',
                    options: {sourceMap: true}
                }
            ]
        }
    ]
}

这三种loader的写法,末了打包的效果雷同

loader中的options设置项能够用”?”跟在加载器背面

eg:

{  
    test: /\.jpeg$/,  
    use: 'url-loader?limit=1024&name=[path][name].[ext]&outputPath=img/&publicPath=output/',  
}

为以下设置的简写

{  
    test: /\.jpeg$/,  
    use: {
        loader:'url-loader',
        options:{
            limit:1024,
            name:[path][name].[ext],
            outputPath:img/
            publicPath:output/'
        }
    }
}

开辟必备的loader&plugins

  • css-loader
  • babel-loader

讲ES6代码转换为ES5

{
    test: /\.js/,
    use: {
        loader: 'babel-loader',
        query: {
            presets: ["env", "stage-0", "react"]
        }
    }
},

babel-loader的预设能够增加在query中,也能够在项目根目次增加 .babelrc 文件

.babelrc

{
    "presets": [
        "env",
        "stage-0",
        "react"
    ]
}
  • html-webpack-plugin

插件的基础作用就是天生html文件。道理很简单:

将 webpack中
entry设置的相干进口thunk 和
extract-text-webpack-plugin抽取的css款式 插进去到该插件供应的
template或许
templateContent设置项指定的内容基础上天生一个html文件,细致插进去体式格局是将款式
link插进去到
head元素中,
script插进去到
head或许
body中。

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

new HtmlWebpackPlugin({
    template: './src/index.html',//指定产的HTML模板
    filename: `index.html`,//产出的HTML文件名
    title: 'index',
    hash: true,// 会在引入的js里到场查询字符串防止缓存,
    minify: {
        removeAttributeQuotes: true
    }
}),

能够用 cnpm search html-webpack-plugin 查找想用loader的用法

  • less-loader sass-loader

优化向prd进发

  • 提取大众的css代码

它会将一切的进口 chunk(entry chunks)中援用的 *.css,移动到自力星散的 CSS 文件。因而,你的款式将不再内嵌到 JS bundle 中,而是会放到一个零丁的 CSS 文件(即 styles.css)当中。 假如你的款式文件大小较大,这会做更快提早加载,由于 CSS bundle 会跟 JS bundle 并行加载。

npm i extract-text-webpack-plugin@next -D
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
let cssExtract = new ExtractTextWebpackPlugin({
    filename: 'css/css.css',
    allChunks: true
});
module:{
    rules:[
        {
            test: /\.css$/,//转换文件的婚配正则
            loader: cssExtract.extract({
                use: ["css-loader?minimize"]
            })
        },
    ]
}
plugins:[
    ...... ,
    + cssExtract
]
  • 只管削减文件剖析,用resolve设置文件剖析途径,include
rules: {
    test: /\.js$/,
    loader:'babel-loader',
    include: path.resolve(__dirname, 'src'),//只转换或许编译src 目次 下的文件
    exclude: /node_modules/ //不要剖析node_modules
}
  • resolve.mainFields
WebpackTest
|
|
| - src
|   | - index.js
|
| - lib
|   | - fetch
|       |
|       browser.js
|       node.js
|       package.json
|
| - webpack.config.js

当从 npm 包中导入模块时(比方,引入lib下的库),此选项将决定在 package.json 中运用哪一个字段导入模块。依据 webpack 设置中指定的 target 差别,默许值也会有所差别。

package.json

lib文件夹下的package.json中设置相对应模块的key

{
  "name": "fetch",
  "version": "1.0.0",
  "description": "",
  "node": "./node.js",
  "browser": "./browser.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

webpack.config.js

在resolve剖析对象中,到场lib的途径

resolve: {
    extensions: ['.js', '.json'],
    mainFields: ['main', 'browser', 'node'],
    modules: [path.resolve('node_modules'), path.resolve('lib')]
}

index.js

如许在index.js中援用第三方库时,会去查找modules下的途径中是不是设置了所需的文件,晓得在package.json中找到mainFields中的key对应文件,住手。

let fetch = require('fetch');
console.log(fetch);

打包后 console.log出的对象
《webpack v4 从dev到prd》

假如交流mainFields中的key递次

mainFields: ['main', 'node','browser']

打包后 console.log出的对象,由于找到了key=node对应的文件就住手了查找

《webpack v4 从dev到prd》

  • DllReferencePlugin

这个插件是在 webpack 主设置文件中设置的, 这个插件把只要 dll 的 bundle(们)(dll-only-bundle(s)) 援用到须要的预编译的依靠。

新建webpack.react.config.js

const path = require('path');
const webpack = require('webpack')
module.exports = {
    entry: {
        react: ['react', 'react-dom']
    },
    output: {
        path: path.join(__dirname, 'dist'),// 输出动态衔接库的文件名称
        filename: '[name]_dll.js',
        library: '_dll_[name]'//全局变量的名字,其它会今后变量上猎取到里面的模块
    },
    // manifest 示意一个形貌文件
    plugins: [
        new webpack.DllPlugin({
            name: '_dll_[name]',
            path: path.join(__dirname, 'dist', 'manifest.json')//末了打包出来的文件目次和名字
        })
    ]
}
在entry进口写入要打包成dll的文件,这里把体积较大的react和react-dom打包

output中的关键是library的全局变量名,下文细致申明dll&manifest事情道理

打包dll文件

webpack --config webpack.react.config.js --mode development

打包出来的manifest.json节选

《webpack v4 从dev到prd》

打包出来的react_dll.js节选

《webpack v4 从dev到prd》

可见manifest.json中的 name值就是

output:{
    library:_dll_react
}

manifest.json就是借书证,_dll_react就像藏书楼书本的条形码,为我们终究找到filename为react_dll.js的参考书

运用“参考书”

在webpack.config.js中到场“借书证”

new webpack.DllReferencePlugin({
    manifest: path.join(__dirname, 'dist', 'manifest.json')
})

再运转

webpack --mode development

打包速率明显变快
《webpack v4 从dev到prd》

打包后的main.js中,react,react-dom.js也打包进来了,胜利~

import React from 'react';\n//import ReactDOM from 'react-dom';
 (function(module, exports, __webpack_require__) {

"use strict";
eval("\n\n//import name from './base';\n//import React from 'react';\n//import ReactDOM from 'react-dom';\n//import ajax from 'ajax';\n//let result = ajax('/ajax');\n\n//ReactDOM.render(<h1>{result}</h1>, document.getElementById('root'));\n// fetch fetch.js fetch.json fetch文件夹\n//let fetch = require('fetch');\n//console.log(fetch);\n//let get = require('../dist/bundle.js');\n//get.getName();\nconsole.log('hello');\n\nvar name = 'zfpx';\nconsole.log(name);\nif (true) {\n    var s = 'ssssssssssssssssssssssss';\n    console.log(s);\n    console.log(s);\n    console.log(s);\n    console.log(s);\n}\n\n//# sourceURL=webpack:///./src/index.js?");

/***/ })

/******/ });

未完待续

  • webpack.ProvidePlugin
  • 拷贝静态资本
  • 紧缩css(npm i -D purifycss-webpack purify-css)

以为好玩就关注一下~迎接人人珍藏写批评~~~

    原文作者:wallaceyuan
    原文地址: https://segmentfault.com/a/1190000014094178
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞