nrm use webpack use

npm -i nrm -g installation nrm

nrm ls View Source Address

nrm use npm switch between different source addresses


npm i cnpm -g mounted CNPM

js 

.js .jsx .coffee (intermediate language) .ts (intermediate language) needs to be compiled

css

.css .sass(.scss) .less

 images

.jpg .png .gif .bmp .svg

 Font file fonts 

.svg .ttf .eot .woff .woff2

Template files

.ejs .jade .vue [This is a defining component in webpack the way, with such a recommendation]

Static resource page introduced much later what the problem

1. slow loading pages, because a lot of secondary request to initiate

2. To deal with complex dependencies


How to deal with these two problems

1. consolidation, compression, elves rabbit, base64 encoded picture

2. learned previously may be used requireJS, may also be used webpack solve complex dependencies between individual packets;

What is webpack

The front end of the project build tool, is based on node.js he developed a front-end tool

How perfect solution to the above two kinds of solutions

1. gulp, task-based taskr

2.webpack, it is based on the entire construction project.

Build automation tools by means of webpack the front end, you can achieve the perfect merger of resources, packing, compression, confusion, and many other functions

Describes the process webpack packaged according to the official website of the picture

3.webpack installation

npm i webpack -g mounted WebPACK


// Since Es6 code too advanced, the browser can not resolve, therefore, this line execution error
import $ from "jquery";
//const $=require('jquery')

webpack  ./main.js  ./dist/bundle.js

Compiled version of the problem can not be too high webpack

1.webpack able to handle the interdependence of js files

2.webpack processing js compatibility issues, they advanced, the browser does not recognize turned low, the browser can recognize

Just run the command format: webpack ./src/main.js -o ./dist/bundle.js --mode development

***** change the code was re-packaged, how to solve this problem?

When we enter the command line npm run dev 1. First of all we did not find the form of an order, he developed the entrance and exit 2.webpack went back to the root directory of the project to find a piece called a configuration problem webpack.config.js 3. but to find the configuration file, webpack go back to perform this configuration file parsing, when parsed the execution profile, you get a configuration file, configuration objects around 4. when webpack get the configuration object, you get a configuration object, the development of entrance and exit, and then packaged building;

webpack-dev-sever tool to automatically package compiled function

npm i webpack-dev-server -D put this tool to use after installation dependent on local development projects 2. After installation, usage and webpack this tool commands, exactly the same

node nodemon

webpack webpack-dev-server

3. Since we are in the project, locally installed webpack-dev-server, so I can not think of it as a script command, run powershell directly in the terminal; (only those installed in the global -g tools, in order to perform normal terminal )

4. Note: webpack-dev-server tool, if you want to normal operation, requiring local eye-catching, you must install webpack

5.webpack-dev-server to help us pack bundle generated, .js files are not stored on the disk but the actual physical custodian directly to the computer's memory, so we are in the root directory of the project, could not find this package good bundle.js

6. We can think, webpack-dev-server to packaged file, in a form of virtual hosting to the root of what we project, although we can not see it, however, it is believed, and dist src node_moduels rating, there is an invisible file called bundle.js

html-webpack-plugin pages in memory

js introduced css attention webpack default can only be packaged js file processing type can not deal with other types of non-js files; we need to manually install some third-party loader The proper handling fee if required js file types

When the loader right call calling sequence. 

When we enter webpack command directly in the console, webpack do a bit short

1. First, webpack found that we did not give it the development of entrance and exit in the form of command

2.webpack went back to the project root directory, look for a configuration file called the webpack.config.js

3. When find the configuration file, webpack will to resolve the implementation of this configuration file, when parsed the execution profile, you get a configuration file, configuration objects everywhere

4. When that high webpack configuration object got the inlet and outlet configuration object, formulated, packaged and Construction

cnpm i less-loader -D .less file import this error report 

cnpm i less -D

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

cnpm i sass-loader -D .sass the document introduction being given

cnpm i node-sass -D

In memory, according to the page template developed to generate a memory of home, co-workers automatically packaged bundle injected into the bottom of the page

If you want to configure the plug-in need around the object, to mount a plugins

package.json file

var htmlWebpackPlugin=require('html-webpack-plugin')

webpack.config.js file

 plugins: [
new webpack.HotModuleReplacementPlugin(),
new htmlWebpackPlugin({
template: path.join(__dirname, "./src/index.html"),
filename: "index.html"
})
],

urlloader

By default, webpack can not handle css file url address, whether it is pictures or font library, as long as it can not handle url

cnpm i url-loader file-loader -D


Image processing into base64 use: [ "?. Url-loader limit = false & name = [name] [ext]"] show the path is set to false

limit given value, is the size of the picture, the unit is byte, if we refer to the picture, or greater than Deng Yi given limit value, Ze will not be converted to string base64 format if the picture given fish limit value, Ze will be converted to a string of base64, name = [name]. [ext] reserved character name suffix


[Hash: 8] -. [Name] [ext] if the picture is the same as the name of the process, when the package back to the picture of the same name appears to retain only one so to add hash: 8
 {
test: /\.(jpg|png|gif|bmp|jpeg)$/,
use: ["url-loader?limit=false&name=[hash:8]-[name].[ext]"]
} /

Handle fonts

If desired in the form of the path, to the introduction of node_modules relevant files can be directly in front of this layer is omitted node_modules directory path, directly write the name of the package, and then to keep the specific file path back

// do not write this node_modules a directory, the default will be to find node_modules

import 'bootstrap/dist/css/bootstrap.css'

{
test: /\.(ttf|eot|svg|woff|woff2)$/,
use: ["url-loader"]
}

webpack babel

class Person{


static info ={

name:'ddd',age:12

}}

es6  webpack

In webpack, the default can only deal with part of the new syntax Es6, and some more advanced Es6 or ES7 grammar, webpack is not treated, this time you need the aid of third-party loader to help webpack deal with these advanced grammar, when the first after the tripartite loader bar high-level syntax into low-level syntax, the result will go to me webpack packed into bundle.js

By babel can help us to convert low-level syntax to syntax.

1. In webpack can run the following command to install two sets of packages, to install the loader functions related babel

 {
test: /\.js$/,
use: ["babel-loader"]
}

The first set of package: cnpm i babel-core babel-loader babel-plugin-transform-runtime -D

Only conversion, do not know the relationship between

A second set of package: cnpm i babel-preset-env babel-preset-stage-0 -D

The syntax can know the relationship between

2. Open webpack profile in the rules array of module node, add a new matching rules:

 {
test: /\.js$/,
use: "babel-loader",exclude:/node_modules/
}

Note: 1. When the loader configuration babel rules, must node_modules catalog, through exclude options exclude: There are two reasons: 1. If you do not exclude node_modules, all third-party js file babel will node_modules in both packaged compiler, so that will be very consuming CPU, while the packaging is very slow 2. even if the final, babel js to convert all of node_modules finished, but the project can not function properly

3. In the root directory of the project, the new one called. babelrc of babel profile, this profile belongs to json format, so when writing .babelrc configuration must comply with the json syntax specification, can not write comments, strings must spend quotes,

3 arranged in the following written .babelrc: {

"presets":["env","stage-0"],

"plugins":["transform-runtime"]

}


Components vue conponent registration of the components will be added in the id

Components render register, id will be deleted, replaced

Vue in use in webpack

In webpack using import Vue from 'vue' introduced Vue constructor function is not complete, only the runtime-only manner, does not provide as use as the Web

Recalling the lookup rules package:

1. To find the root of the project folder there node_modules

2. In node_modules according to the application, find the corresponding folder vue

3. vue folder, look for a package configuration file named package.json

4. In package.json file, look for a main properties (main property developed this package in the file entry is caught in time)

If vue 1. To use the page can be changed directly introduced into the main inlet package.json file directly to vue.js

2. paths to import Vue from '../node_modules/vue/dist/vue.js'


3.webpack.config.js configure

resolve:{

 alias:{

"vue$":"vue/dist/vue.js"

}

}


The default webpack, can not be packaged vue file, you need to manually install the relevant loader

CNPM view i-loader-template-view compile -D

In the configuration file, add, loader configuration item


the node member exposed outward form:

//module.exports={}

In the Es6, Cecilia over canonical form, specifies how to import and export module

Es6 import module, use the import module name from 'represents a module identifier' import 'represents the path'

Using default or export the export Es6 member exposed outwardly export default is exposed to the introduced time can easily take the name, in a module, the default export only once exposed outwardly, in a module can be used to export and export default

Use export outwardly exposed members can only accept the use of the form {} import {title} from "test.js", this form is called export demand, export plurality of members may be exposed outwardly, while, if some members we import, when not required, Ze can no longer be defined in {}, using export exported members, must be exported by name in accordance with a time to use the received demand {} {title as t} use as taken alias export exported members, if wanted to change the name to receive, can be used as an alias to take


// var name = require the use of the Node ( 'module identifier')

////module.exports and exports

vue-router

el will render the specified container, cover all of the contents are emptied, so do the route touter-view router-link and write directly controlled container el

This component had deemed App VM rude render the render function, render function if the component to be rendered, only put el: 'app' designated element,

// account and goodsList assembly, is monitored by the route so these two components, only appear to belong to route <router-view> </ router-view> go

.vue <style scoped></style>

Ordinary style only supports plain style, if you want to enable scss or less need to set the lang attribute to the style element

lang="scss"


webpack release strategy

webpack.config.js

webpack.pub.config.js

"pub":"webpack --config webpack.pub.config.js"

Packaged picture into images

{
test: /\.(jpg|png|gif|bmp|jpeg)$/,
use: ["url-loader?limit=false&name=images/[hash:8]-[name].[ext]"]
},

yarn add clean-webpack-plugin --dev each release empty folder dist

Import plug-delete every folder

const cleanWebpackPlugin=require('clean-webpack-plugin')

  plugins: [

new cleanWebpackPlugin(['dist'] ),

]

Publish ideas, bundle.js only store their own code, code that third-party packages, all pulled in to another js


const webpack =require('webpack')

entry: {
app:path.join(__dirname, "./src/main.js"), //入口
vendors1: [ "jquery", 'vue'] // store a third party package
}
  plugins: [

new webpack.optimize.CommonsChuckPlugin({

name: 'vendors1', // name to be pulled out of the entrance of the development

filename:'vendors.js'

})

 
]

Compressed code


 plugins: [

new webpack.optimize.UglifyJsPlugin({

compress:{

warnings:false

}


}),

// set the upper limit of the environment, jinx a compressed code

new webpack.optimize.DedupePlugin({

"process.env.NODE_ENV":'"production"'


}),

]

html code compression


new htmlWebpackPlugin({
template: path.join(__dirname, "./src/index.html"),
filename: "index.html",

minify:{

collapseWhitespace:true,

removeComments:true,

removeAttributeQuotes: true // remove the double quotes on the property

}

}),

Css extraction plug

yarn add extract-text-webpack-plugin --dev


{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
}),
publicPath: '../'

}, The image path may be extracted not, be treated with publicPath


style compression

cnpm i optimize-css-assets-webpack-plugin --save-dev

var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

new OptimizeCssAssetsPlugin () // CSS file compression plug-ins



Reproduced in: https: //juejin.im/post/5d02464b6fb9a07eed34fa6a

Guess you like

Origin blog.csdn.net/weixin_33964094/article/details/93166446