webpack4 series first article (study notes)

Preface: I will try to write more detailed, because I know I lost learning time.

First, what is webpack

In simple terms, webpack can be seen as a packer module, packaged as a static resource files through the inlet in accordance with the dependencies between individual files (like js, css, images, etc.).


2063593-7709b214db3733bf.jpg
webpack.jpg
What can you do webpack

Transcoding (such es6 switch ES5), optimization of the file, the code separation, merge module, automatic refresh, the code verification is automatically released and the like. See https://www.webpackjs.com/concepts/

Ado, and quickly look at how to use it!

Second, the zero configuration experience

1, npm initinitializing a project.
2, local installation (not recommended to install global, global installation will lead to many problems because of the different versions)
npm install --save-dev webpack webpack-cli
3, the root directory create a src folder, build a index.js file under src. Now the directory structure is as follows:

2063593-4a0b1079c77ada6f.jpg
The initial directory structure .jpg

Beginning of the article said webpack packer is a module that first to experience its packaging function.
We write a word in index.js years:
console.log('hello webpack!')
then execute the following command line to package (Note: npx is npm 5.2 new)
npx webpack
to look at what changes
2063593-f9c8746517c33a18.jpg
1559119543(1).jpg

End execution npx webpack after the discovery of more than a folder dist, dist folder has a main.js, which code has been packaged compressed.
A closer look, I only write one sentence index.js file, but after more than a pack so much code, which is why? The reason is that webpack automatically when the modular packaging.
Since webpack automatically when the modular package, then we have to write a module to see.
In a new src a.js, with module.exports export, then index.js require come:
a.js:

module.exports  = 'hello webpack from a.js'

index.js:

let str = require('./a.js')
console.log(str)

Then re-execute the command line npx webpackto package and found a man called modesomething, modeis webpack4 a new configuration, called "mode" by default production(production model), may also be development(development mode), developmentmode does not compress the code, Some easier to read.

2063593-1832dd426610fd3c.jpg
1559183315(1).jpg

If you want npm run build to have to perform, then only you need to configure the package.json in the script script. Like this:

  "scripts": {
    "build": "webpack --config webpack.config.js"
  }

Of course, build a name for themselves, too, you can also play other names.
We temporarily in the dist directory manually create a index.htmland main.js introduced (automatically generates html say later) after the packaging:
index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="main.js"></script>
</body>
</html>

Index.html will open in your browser, console you can see there are 'hello webpack from a.js' up.
Zero Configuration is weak, more complex requirements, also need to be manually configured.

Third, the manual configuration webpack

The default configuration file name: webpack.config.js(node uses syntax to write), the new one in the root directorywebpack.config.js

const path = require('path')
module.exports = {
    entry: './src/index.js', //入口文件
    output: {
        filename: 'bundle.[hash].js', //默认为main.js 
        path: path.resolve(__dirname,'./dist') //path为绝对路径,用node path模块转化
    },
    mode: 'development' //开发模式
}

[hash] js cache is to avoid such modification will produce a result file redundancy, you can install clean-webpack-plugin to clear the previous version:
npm i clean-webpack-plugin -D
webpack.config.js in introducing

const CleanWebpackPlugin = require('clean-webpack-plugin')
    plugins:[ //存放插件
        new CleanWebpackPlugin()
    ]

At this time webpack.config.js:

const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {
    entry: './src/index.js', //入口文件
    output: {
        filename: 'bundle.[hash].js', //默认为main.js  [hash]是为了避免js缓存
        path: path.resolve(__dirname,'./dist') //path为绝对路径,用node path模块转化
    },
    mode: 'development', //开发模式
    plugins:[ //存放插件
        new CleanWebpackPlugin(['./dist'])
    ]
}

Delete dist folder, and then run it npm run build, you will find packaged under dist folder out of a build.js, the contents inside the default mode of production and packaging out of the content is different, this time packed out of the relatively large size of the code but easier to read.

2063593-bd3c559fbebfa762.jpg
1559195248(1).jpg

Then again dist directory under a new index.html and the introduction of packaged build.js, opened in a browser, the console can still see the correct output.
But each time the html file manually add too much trouble, can automatically generate packing when it? html-webpack-plugin Plug-in can be achieved

Package automatically generates html

1, first install
npm i html-webpack-plugin -D
2, the new html template under src

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>webpack</title>
</head>
<body>
    
</body>
</html>

3, webpack.config.js in the introduction

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

4, webpack.config.js plugins module adds HtmlWebpackPlugin

    plugins:[ //存放插件
        new HtmlWebpackPlugin({
            template: './src/index.html', //模板
            filename: 'index.html', //默认也是index.html
            minify: {
                removeAttributeQuotes: true, //删除标签属性的双引号
                collapseInlineTagWhitespace: true, //打包成一行
            },
            hash: true, //增加hash,避免缓存
        }),
        new CleanWebpackPlugin(['./dist'])
    ]

At this time, execution then delete folder dist npm run buildpackaged, will find that the finished folder dist index.html has been generated and automatically introduces bundle.js. Index.html opens in a browser, the console can still see the normal output.
Open every html in the document, this is a little low, so we have to configure a local server it!

Configure the local development server

1, or the first installation
npm i webpack-dev-server -D
we also need to configure devServer in webpack.config.js in.

    devServer:{ //开发服务器配置
        port: 3000, //端口号
        progress: true, //进度条
        contentBase: './dist', //服务默认指向文件夹
        open: true //自动打开浏览器
    }

This service can be started by npx webpack-dev-server, package.json scripts can also be configured in the script:

"dev": "webpack-dev-server"

The so npm run devas to start the development environment.
Currently the scripts to configure the two scripts

  "scripts": {
    "build": "webpack --config webpack.config.js",
    "dev": "webpack-dev-server"
  }

Run npm run dev, the browser automatically open a service. Open the console can still see the normal output.

webpack default only supports js, css I also want to pack how to do? See next webpack4 The second series

Guess you like

Origin blog.csdn.net/weixin_33890526/article/details/90912723
Recommended