Home > Web Front-end > JS Tutorial > body text

Web example code for building front-end projects using webpack

小云云
Release: 2018-02-02 13:25:12
Original
2922 people have browsed it

The most popular ones nowadays are webpack and gulp. We talked about gulp in the previous article. In this article, we will discuss webpack. This article mainly introduces to you how to use webpack to build front-end projects on the Web. I think it is quite good. Now Share it with everyone and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Speaking of webpack, front-end students must be familiar with it. In fact, when we used gulp to build before, we also used webpack’s packaging technology. Gulp and webpack do not replace each other, but complement each other. Today we will take a closer look at the magic of webpack.

When we learn a new technology, we must first start with its official documentation. Of course, we have to learn the latest version. The official tutorial of webpack is very well written and explains it step by step. Students can read the official documentation directly. Compared with the second-hand, third-hand and fourth-hand information in the blog, the official tutorial Documentation is definitely a better choice for you.

This article is not about teaching you how to copy official documents, such as reading this article is enough, but it allows you to get started quickly and feel the so-called In fact, webpack is just like this. With webpack, you only need to remember one central idea, just like the above diagram, it packs and compresses all the intricate file logic into several static resources. Without further explanation, let’s look at the code. It’s practical.

webpack.config.js

For some front-end developers who have abandoned jquery and embraced react and vue, although webpack may not have been written by themselves, But you have probably seen it before. Generally speaking, there will be a webpack configuration file of webpack.config.js. The following code is a simple webpack configuration, although it is small, it has all the essentials.


var debug = process.env.NODE_ENV !== "production"; //是否是测试环境
var webpack = require('webpack'); //导入webpack包
var path = require('path');

module.exports = { //导出 webpack固定写法
 context: path.join(__dirname),
 devtool: debug ? "inline-sourcemap" : null, //是否使用map工具, 用于浏览器debug
 entry: "./src/js/root.js", //打包的实体
 module: {
  loaders: [ //加载的配置
   {
    test: /\.js?$/,
    exclude: /(node_modules)/,
    loader: 'babel-loader',
    query: {
     presets: ['react', 'es2015'], //添加预处理器
     plugins: ['react-html-attrs'], //添加组件的插件配置
    }
   },
   { test: /\.css$/, loader: 'style-loader!css-loader' },
   {
    test: /\.less$/,
    loader: "style!css!less"
   }
  ]
 },
 output: { //输出的路径及文件名
  path: __dirname,
  filename: "./src/bundle.js"
 },
 plugins: debug ? [] : [ //一些插件
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
 ],
};
Copy after login

Webpack mainly includes four major categories: entry, module, output, plugins. The official documentation is very clear. If you want to learn more, Please read the official documentation. If you don’t want to bother, just copy the above code.

Compared with gulp, webpack is more streamlined in terms of packaging. This is probably why it is popular, but just looking at the above files, it is indeed simple. , but there is still room for further improvement.

package.json

I won’t say much about the introduction of npm, let’s look at the file directly.


{
 "name": "webpack",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": { //命令行工具
  "test": "echo \"Error: no test specified\" && exit 1",
  "watch": "webpack --progress --watch",
  "start": "webpack-dev-server --open --config webpack.dev.js",
  "build": "webpack --config webpack.prod.js"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "devDependencies": { //开发环境依赖
  "babel-loader": "^7.1.2",
  "clean-webpack-plugin": "^0.1.16",
  "css-loader": "^0.28.7",
  "csv-loader": "^2.1.1",
  "file-loader": "^0.11.2",
  "html-webpack-plugin": "^2.30.1",
  "json-loader": "^0.5.7",
  "lodash": "^4.17.4",
  "style-loader": "^0.18.2",
  "uglifyjs-webpack-plugin": "^0.4.6",
  "webpack": "^3.6.0",
  "webpack-dev-middleware": "^1.12.0",
  "webpack-dev-server": "^2.8.2",
  "webpack-merge": "^4.1.0",
  "xml-loader": "^1.2.1"
 },
 "dependencies": { //生产环境依赖
  "babel-plugin-import": "^1.5.0",
  "babel-plugin-react-html-attrs": "^2.0.0",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-react": "^6.24.1",
  "babelify": "^7.3.0",
  "react": "^15.6.1",
  "react-dom": "^15.6.1",
  "react-mixin": "^4.0.0",
  "react-router": "^4.2.0"
 }
}
Copy after login

The command line tool is npm run build which is equivalent to executing webpack --config webpack.prod.js, and npm start is equivalent to executing webpack-dev-server --open --config webpack.dev.js. It’s simple and easy to understand.

In the project dependencies, we have added a lot of plug-ins and loaders, which are all used to build webpack. They are all mentioned in the tutorials of the official documents. It is worth it. What we should pay attention to is the webpack-merge package. This package allows us to isolate the configuration of the production environment and the development environment very well. Let’s see how to do it?

First we need to divide the previous webpack.config.js into Three files --- webpack.common.js, webpack.dev.js, webpack.prod.js.

webpack.common.js

This is webpack The common configuration is generally the same as what we saw before. We mainly imported two plug-ins, one is the cleaning plug-in, and the other is the plug-in for creating html.


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

module.exports = {
 entry: './src/index.js',
 plugins: [
  new CleanWebpackPlugin(['dist']),
  new HtmlWebpackPlugin({title: 'webpack'}),
  new webpack.HashedModuleIdsPlugin()
 ],
 output: {
  filename: '[name].[chunkhash].js',
  path: path.resolve(__dirname, 'dist')
 },
 module: {
  rules: [
   {
    test: /\.js?$/,
    exclude: /(node_modules)/,
    loader: 'babel-loader',
    query: {
     presets: [
      'react', 'es2015'
     ],
     plugins: ['react-html-attrs']
    }
   },
   {
    test: /\.css$/,
    use: ['style-loader', 'css-loader']
   }, {
    test: /\.(png|svg|jpg|gif)$/,
    use: ['file-loader']
   }, {
    test: /\.(woff|woff2|eot|ttf|otf)$/,
    use: ['file-loader']
   }, {
    test: /\.(csv|tsv)$/,
    use: ['csv-loader']
   }, {
    test: /\.xml$/,
    use: ['xml-loader']
   }
  ]
 }
};
Copy after login

rulesIn the configuration, we also configure some files that may be used into webpack. babel-loaderIf you want to talk about this, you can write another article, it is actually a js Compatibility tool, you can understand it this way.

webpack.dev.js

The configuration of the webpack development environment is very simple, just use the webpack mentioned before -The merge tool, just like git, merges the configuration of webpack.common.js and adds an inline-source-map tool for debugging and a hot update content index.


const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
 devtool: 'inline-source-map',
 devServer: {
  contentBase: './dist'
 }
});
Copy after login

webpack.prod.js

Configuration of webpack production environment, a new compression plug-in and environment configuration plug-in are added. Here are the development tools and development repayments. are different, please refer to the official documentation directly.


const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
 devtool: 'source-map',
 plugins: [
  new UglifyJSPlugin({sourceMap: true}),
  new webpack.DefinePlugin({
   'process.env': {
    'NODE_ENV': JSON.stringify('production')
   }
  })
 ]
});
Copy after login

terminal

In this way, we have completed the configuration. We are Enter on the terminal to see the effect:


cd ../ && npm i
Copy after login

First we enter the directory and install the node package.

npm run build


MacBook-Pro-15:webpack zhushuangquan$ npm run build

> webpack@1.0.0 build /Users/zhushuangquan/Documents/code/webpack
> webpack --config webpack.prod.js

clean-webpack-plugin: /Users/zhushuangquan/Documents/code/webpack/dist has been removed.
Hash: 85b65f54ef1436b295a5
Version: webpack 3.6.0
Time: 1148ms
              Asset    Size Chunks       Chunk Names
  main.014ac9aa420264da48eb.js 671 bytes    0 [emitted] main
main.014ac9aa420264da48eb.js.map  6.47 kB    0 [emitted] main
           index.html 197 bytes     [emitted] 
[lVK7] ./src/index.js 184 bytes {0} [built]
Child html-webpack-plugin for "index.html":
   1 asset
  [3IRH] (webpack)/buildin/module.js 517 bytes {0} [built]
  [DuR2] (webpack)/buildin/global.js 509 bytes {0} [built]
    + 2 hidden modules
Copy after login

We can see the packaged files:

main.014ac9aa420264da48eb.js


!function(e){function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}var t={};n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n(n.s="lVK7")}({lVK7:function(e,n,t){"use strict";document.body.appendChild(function(){var e=document.createElement("p");return e.innerHTML="Hello webpack",e}())}});
//# sourceMappingURL=main.014ac9aa420264da48eb.js.map
Copy after login

We can see that under the packaging and compression of webpack, the code is basically unreadable. So we need to add the previous debugging plug-in to remedy bugs in the production environment.

npm start


MacBook-Pro-15:webpack zhushuangquan$ npm start

> webpack@1.0.0 start /Users/zhushuangquan/Documents/code/webpack
> webpack-dev-server --open --config webpack.dev.js

clean-webpack-plugin: /Users/zhushuangquan/Documents/code/webpack/dist has been removed.
Project is running at http://localhost:8080/
webpack output is served from /
Content not from webpack is served from ./dist
webpack: wait until bundle finished: /
Hash: 06f20ec519d58fbd5c28
Version: webpack 3.6.0
Time: 1460ms
            Asset    Size Chunks          Chunk Names
main.5eb4d4e3f458c49658a2.js   852 kB    0 [emitted] [big] main
         index.html 197 bytes     [emitted]     
[6Um2] (webpack)/node_modules/url/util.js 314 bytes {0} [built]
[8o/D] (webpack)-dev-server/client/overlay.js 3.71 kB {0} [built]
[HPf+] (webpack)/node_modules/url/url.js 23.3 kB {0} [built]
[Lx3u] (webpack)/hot/log.js 1.04 kB {0} [optional] [built]
[Sj28] (webpack)-dev-server/node_modules/strip-ansi/index.js 161 bytes {0} [built]
[TfA6] (webpack)/hot nonrecursive ^\.\/log$ 170 bytes {0} [built]
[U2me] (webpack)/hot/emitter.js 77 bytes {0} [built]
[V3KU] (webpack)-dev-server/client/socket.js 1.04 kB {0} [built]
[cMmS] (webpack)-dev-server/client?http://localhost:8080 7.27 kB {0} [built]
[gqsi] (webpack)-dev-server/node_modules/loglevel/lib/loglevel.js 7.74 kB {0} [built]
  [0] multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js 40 bytes {0} [built]
[gt+Q] (webpack)-dev-server/node_modules/ansi-regex/index.js 135 bytes {0} [built]
[lVK7] ./src/index.js 184 bytes {0} [built]
[p7Vd] (webpack)/node_modules/punycode/punycode.js 14.7 kB {0} [built]
[pEPF] (webpack)/node_modules/querystring-es3/index.js 127 bytes {0} [built]
  + 73 hidden modules
Child html-webpack-plugin for "index.html":
   1 asset
  [3IRH] (webpack)/buildin/module.js 517 bytes {0} [built]
  [DuR2] (webpack)/buildin/global.js 509 bytes {0} [built]
  [M4fF] ./node_modules/lodash/lodash.js 540 kB {0} [built]
  [a/t9] ./node_modules/html-webpack-plugin/lib/loader.js!./node_modules/html-webpack-plugin/default_index.ejs 538 bytes {0} [built]
webpack: Compiled successfully.
Copy after login

We can see that a webpage with the content Hello webpack is opened on port 8080. When we modify the file, the webpage will automatically refresh.

Knowledge points:

Go back to our command line configuration of package.json just now.


 "scripts": { //命令行工具
  "test": "echo \"Error: no test specified\" && exit 1",
  "watch": "webpack --progress --watch",
  "start": "webpack-dev-server --open --config webpack.dev.js",
  "build": "webpack --config webpack.prod.js"
 },
Copy after login
  • 上面的npm run build => webpack => webpack.prod.js, 就是执行了生产环境的配置的打包命令.

  • 上面的npm start => webpack-dev-server --open => webpack.dev.js, 就是执行了开发环境配置的服务端命令.

  • --config是用于执行webpack配置文件的命令, 而默认为webpack.config.js.

  • webpack命令就是和之前的gulp的逻辑相似, 将entry实例复制到output路径的逻辑. 当然还伴随着一系列的操作.

  • webpack-dev-server --open命令是打开服务器并进行热加载的用途.

以上就是webpack的使用及逻辑, 并没有想象中的复杂吧, 甚至可以说是简单, 实测一天即可入门webpack.

由于webpack的配置是固定代码, 我已经打包上传github, 需要的同学可以进行下载.

相关推荐:

实例详解vue-cli中的webpack配置

webpack配置方法小结

如何使用 webpack 优化资源方法技巧

The above is the detailed content of Web example code for building front-end projects using webpack. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template