Table of Contents
Big changes" >Big changes
Load loader method summary" >Load loader method summary
Develop necessary loader&plugins" >Develop necessary loader&plugins
Optimize towards prd " >Optimize towards prd
未完待续" >未完待续
Home Web Front-end JS Tutorial Detailed explanation of usage from dev to prd

Detailed explanation of usage from dev to prd

May 02, 2018 pm 02:33 PM
use Detailed explanation

This time I will bring you a detailed explanation of the use from dev to prd, and what are the precautions when using from dev to prd. The following is a practical case, let's take a look.

This article is used to learn new features and summarize the must-use plugins & loaders for development, from dev to prd, it’s up to you~

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

The mode configuration item is introduced in this new version. Developers can choose between none, development (development) and production (product) modes. This configuration item uses production mode by default.

  1. The development mode gives you the ultimate development experience, including browser debugging related tools, extremely fast incremental compilation, and rich and comprehensive error information...

  2. The production mode includes a lot of release optimization, code compression, smooth runtime optimization, elimination of development-related code, ease of use, etc.

  3. none No Using the default is equivalent to the original state of all self-configurations in the old version.

#eg:

webpack --mode development
Copy after login
Copy after login

Usage

  1. Some Plugin options are now validated

  2. CLI has been move to webpack-cli, you need to install webpack-cli to use the CLI

  3. The ProgressPlugin (--progress) now displays plugin names

  4. At least for plugins migrated to the new plugin system

In the new version, the webpack command line tool is split into a separate warehouse, so additional installation of webpack is required- cli.

npm init -y //初始化项目
npm install webpack webpack-cli -D //安装webpack webpack-cli 依赖
npx webpack --mode development // npx可以直接运行node_modules/.bin目录下面的命令
Copy after login

Or configure the script build of package.json

"scripts": {
 "build": "webpack --mode development",
},
Copy after login

Load loader method summary

use

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

css-loader is used to parse and process the url path in the CSS file, and turn the CSS file into a module

Multiple loaders are required in order, written from right to left, because when converting It is converted from right to left

This plug-in first uses css-loader to process the css file, and then uses style-loader to turn the CSS file into a style tag and insert it into the head

loader

module: {
 rules:[
  {
   test: /\.css$/,
   loader: ["style-loader", "css-loader"]
  },
 ]
}
Copy after login

use loader

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

These three ways of writing loaders have the same final packaging results

The options configuration item in the loader can be followed by "?" after the loader

eg:

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

is the abbreviation of the following configuration

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

Develop necessary loader&plugins

  1. css-loader

  2. babel-loader

Talk about converting ES6 code to ES5

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

babel-loader's preset can be added to the query , you can also add a .babelrc file in the project root directory

.babelrc
{
 "presets": [
  "env",
  "stage-0",
  "react"
 ]
}
Copy after login

html-webpack-plugin

The basic function of the plug-in is to generate html files. The principle is very simple:

Insert the relevant entry thunk of the entry configuration in webpack and the css style extracted by extract-text-webpack-plugin into the template provided by the plug-in or the content specified by the templateContent configuration item to generate an html file, the specific insertion method is to insert the style link into the head element and the script into the head or 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
 }
}),
Copy after login

You can use cnpm search html-webpack-plugin to find the usage of loader

less-loader sass-loader

Optimize towards prd

Extract common css code

It will move the *.css referenced in all entry chunks (entry chunks) to independent and separate CSS files. Therefore, your styles will no longer be embedded in the JS bundle, but will be placed in a separate CSS file (i.e. styles.css). If your style files are larger in size, this will make early loading faster because the CSS bundle will be loaded in parallel with the JS bundle.

npm i extract-text-webpack-plugin@next -D
Copy after login
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
let cssExtract = new ExtractTextWebpackPlugin({
 filename: 'css/css.css',
 allChunks: true
});
Copy after login
module:{
 rules:[
  {
   test: /\.css$/,//转换文件的匹配正则
   loader: cssExtract.extract({
    use: ["css-loader?minimize"]
   })
  },
 ]
}
plugins:[
 ...... ,
 + cssExtract
]
Copy after login

尽量减少文件解析,用resolve配置文件解析路径,include

rules: {
 test: /\.js$/,
 loader:'babel-loader',
 include: path.resolve(dirname, 'src'),//只转换或者编译src 目录 下的文件
 exclude: /node_modules/ //不要解析node_modules
}
Copy after login

resolve.mainFields

WebpackTest
|
|
| - src
| | - index.js
|
| - lib
| | - fetch
|  |
|  browser.js
|  node.js
|  package.json
|
| - webpack.config.js
Copy after login

当从 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"
}
Copy after login

webpack.config.js

在resolve解析对象中,加入lib的路径

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

index.js

这样在index.js中引用第三方库时,会去查找modules下的路径中是否配置了所需的文件,知道在package.json中找到mainFields中的key对应文件,停止。

let fetch = require('fetch');
console.log(fetch);
Copy after login

打包后 console.log出的对象

如果交换mainFields中的key顺序

mainFields: ['main', 'node','browser']
Copy after login

打包后 console.log出的对象,因为找到了key=node对应的文件就停止了查找

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')//最后打包出来的文件目录和名字
  })
 ]
}
Copy after login

在entry入口写入要打包成dll的文件,这里把体积较大的react和react-dom打包

output中的关键是library的全局变量名,下文详细说明dll&manifest工作原理

打包dll文件

webpack --config webpack.react.config.js --mode development
Copy after login

打包出来的manifest.json节选

打包出来的react_dll.js节选

可见manifest.json中的 name值就是

output:{
  library:_dll_react
}
Copy after login

manifest.json就是借书证,_dll_react就像图书馆书籍的条形码,为我们最终找到filename为react_dll.js的参考书

使用“参考书”

在webpack.config.js中加入“借书证”

new webpack.DllReferencePlugin({
  manifest: path.join(dirname, 'dist', 'manifest.json')
})
Copy after login

再运行

webpack --mode development
Copy after login
Copy after login

打包速度显著变快

打包后的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?");
/***/ })
/******/ });
Copy after login

未完待续

  1. webpack.ProvidePlugin

  2. 拷贝静态资源

  3. 压缩css(npm i -D purifycss-webpack purify-css)

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

webpack中dev-server使用步骤详解

Angular2中如何使用Dom

The above is the detailed content of Detailed explanation of usage from dev to prd. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

See all articles