Home Web Front-end JS Tutorial How to use Webpack to develop projects

How to use Webpack to develop projects

May 31, 2018 pm 02:39 PM
web webpack conduct

This time I will show you how to use Webpack to develop projects, and what are the precautions for using Webpack to develop projects. The following is a practical case, let's take a look.

1. Introduction to common packaging tools

Among the packaging tools, the common ones are RequireJS, browserify, and webpack, among which RequireJS is a

JavaScriptModule loader, based on the ADM (async module define) specification implementation, browserify is a tool based on using Node.js modules in the browser, and webpack is a tool for packaging and building front-end modules. Generated tools.

2. Use of tools

(1) RequireJS as an npm package provides an executable r.js The tool is executed through the command line and is used as follows:

npm install -g requirejs
r.js -o app.build.js
Copy after login
(2) The command line tool provided by browserify is used as follows:

npm install -g browserify
browserify main.js -o bundle.js
Copy after login
(3) The use of webpack

As shown below, use the command to install and use it, as shown below:

npm install webpack -g
webpack main.js -o bundle.js
Copy after login
In the above command line, we performed a simple global installation of webpack and packaging of the main.js file

3. Project construction

For front-end projects, webpack plays the role of a build tool, not a code dependency, and should be installed In dev-dependencies, use the following command to install:

npm install webpack --save-dev
Copy after login
In this example, a simple application will be built, including two js modules

1. Generate the text "Hello world" The hello module (hello.js)

module.exports = 'Hello world';
Copy after login
2. The index.js module (index.js)

var text = require('./hello');
console.log(text);
Copy after login
for printing text and index.html for displaying content in the front-end browser File

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script src="./bundle.js"></script>
</body>
</html>
Copy after login
The bundle.js file introduced in the above src path does not exist because it has not been created yet. After using webpack to create the packaged js file, use the following command to create it:

webpack ./index.js bundle.js
Copy after login
After executing the above command, we can see the printed results in the browsing console

Hello world

In this way, we have realized the implementation principle of a simple project , the packaged content is bundle.js, we can see the packaged content, so we won’t post the code here.

Of course, if we write code to build it like this, then it won’t be of much use. , this has to mention another advantage of webpack, that is, the use of

configuration file. Before using the configuration file, we are installing the style loader, such as the following command:

npm install style-loader css-loader --save-dev
Copy after login
Through the above configuration, we can load the style

Then we set the webpack configuration file. We need to first create the webpack.config.js file under the project, the content of which is as follows:

var path = require('path');
module.exports = {
 entry: path.join(dirname, 'index'),
 output: {
  path: dirname,
  filename: 'bundle.js'
 },
 module:{
  loaders: [
   {
    test: /\.css$/,
    loaders: ['style-loader', 'css-loader']
   }
  ]
 }
};
Copy after login
In the above code,

* entry: represents the
entry file of the project * output: represents the result output after building and packaging, there are still multiple items in the output object Configuration such as the output path and output file name used above
* module.loaders is the configuration used for the loader in the module. The value is an array. Each item of the array specifies a rule. The test field of the rule is
Regular expression, if the ID of the dependent module matches the regular expression, the dependency will be converted using loader. In this way, we can use the webpack command to convert the codeFor more detailed instructions, please see ( http://www.jb51.net/article/136710.htm)

The following command line command can be used to package the code

webpack

By executing the above The command can also package files, and the style can also be displayed when displaying the file. In order to prove that the style can indeed be introduced, we create the index.css file, the content of which is as follows:

body {
  background-color: darkgray;
}
Copy after login
Then introduce it into the index.js we created before. The modified code is as follows:

// import style from './index.css';
var style = require('./index.css');
var text = require('./hello');
console.log(text);
Copy after login
In the above code, what is commented out is the import form of the node module, and what is used is CommonJS After using the specification and using the same command to package, we can see the following effect in the browser:

That is, the style is displayed.

当然,webpack也能够通过webpack-dev-server进行项目的实时构建.
使用如下命令进行webpack-dev-server的安装:

npm install webpack-dev-server --save-dev
Copy after login

在安装之后,我们能够配置使用服务器,首先,我们的package.json文件将会更为下面这样,新增内容为:

 "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start":"webpack-dev-server --inline"
 },
Copy after login

在添加完这行命令之后,我们就可以使用下面命令进行启动webpack-dev-server服务器了,

npm run start
Copy after login

之后完整的package.json为如下:

{
 "name": "react-basics-review",
 "version": "1.0.0",
 "description": "a practise of react study ",
 "main": "index.js",
 "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start":"webpack-dev-server --inline"
 },
 "repository": {
  "type": "git",
  "url": "git+https://github.com/suwu150/react-basics-review.git"
 },
 "author": "jkwu",
 "license": "ISC",
 "bugs": {
  "url": "https://github.com/suwu150/react-basics-review/issues"
 },
 "homepage": "https://github.com/suwu150/react-basics-review#readme",
 "devDependencies": {
  "babel-plugin-transform-object-rest-spread": "^6.23.0",
  "babel-preset-es2015": "^6.24.1",
  "css-loader": "^0.28.5",
  "lodash": "^4.17.4",
  "mocha": "^3.5.0",
  "react": "^15.6.1",
  "style-loader": "^0.18.2",
  "webpack": "^3.5.5",
  "webpack-dev-server": "^2.7.1"
 },
 "dependencies": {
  "lodash": "^4.17.4"
 }
}
Copy after login

webpack配置文件修改为如下内容:

devServer中常用的配置对象属性如下:

* 1. contentBase:”./” // 本地服务器在哪个目录搭建页面,一般我们在当前目录即可;
* 2. historyApiFallback:true // 当我们搭建spa应用时非常有用,它使用的是HTML5 History Api,任意的跳转或404响应可以指向 index.html 页面;
* 3. inline:true // 用来支持dev-server自动刷新的配置,webpack有两种模式支持自动刷新,一种是iframe模式,一种是inline模式;使用iframe模式是不需要在devServer进行配置的,只需使用特定的URL格式访问即可;不过我们一般还是常用inline模式,在devServer中对inline设置为true后,当我们启动webpack-dev-server时仍要需要配置inline才能生效,这一点我们之后再说;
* 4. hot:true // 启动webpack热模块替换特性,这里也是坑最多的地方,不少博客都将hot设置了true,这里其实如果单单设置为true是不起作用,会报错误的,错误如下图所示:

 

这是因为在使用的过程中没有使用插件的原因,只需要将下面命令添加到配置文件即可:

plugins:[
  new webpack.HotModuleReplacementPlugin(),
 ],
Copy after login

也就是调用webpack的热模块插件处理.

*5 .port:端口号(默认8080) ;
*6.其他配置信息
–quiet 控制台中不输出打包的信息
–compress 开启gzip压缩
–progress 显示打包的进度
–open 自动打开浏览器

var path = require('path');
const webpack = require ("webpack");
module.exports = {
 entry: path.join(dirname, 'index'),
 output: {
  path: dirname,
  filename: 'bundle.js',
  publicPath: "/assets/",
 },
 module:{
  loaders: [
   {
    test: /\.css$/,
    loaders: ['style-loader', 'css-loader']
   }
  ]
 },
 plugins:[
  new webpack.HotModuleReplacementPlugin(),
 ],
 devServer:{
  //我们在这里对webpack-dev-server进行配置
  contentBase: "./",
  historyApiFallback:true,
  inline:true,
  hot:true
 }
};
Copy after login

index.html文件的内容修改为下面面格式:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<p>身在山中不知山高</p>
<script src="assets/bundle.js"></script>
</body>
</html>
Copy after login

也就是将路径进行修改,因为在webpack.config.json文件中进行了服务器路径的配置,修改了 publicPath: "/assets/",项,在命令行执行npm run start能看到服务器正常启动,然后我们去浏览器进行访问,如下所示结果:

 

至此,我们完成了webpack实时构建的配置,当我们进行修改某一样式文件或者js文件的时候,项目就会重新打包,并且自动刷新加载到浏览器中.

如下面链接提示:,进行实时构建的搭建webpack-dev-server实时搭建

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

推荐阅读:

如何在微信小程序内开发验证码密码输入框功能

如何使用js统计页面标签数量

The above is the detailed content of How to use Webpack to develop projects. 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)

VUE3 Getting Started Tutorial: Packaging and Building with Webpack VUE3 Getting Started Tutorial: Packaging and Building with Webpack Jun 15, 2023 pm 06:17 PM

Vue is an excellent JavaScript framework that can help us quickly build interactive and efficient web applications. Vue3 is the latest version of Vue, which introduces many new features and functionality. Webpack is currently one of the most popular JavaScript module packagers and build tools, which can help us manage various resources in our projects. This article will introduce how to use Webpack to package and build Vue3 applications. 1. Install Webpack

How to use Nginx web server caddy How to use Nginx web server caddy May 30, 2023 pm 12:19 PM

Introduction to Caddy Caddy is a powerful and highly scalable web server that currently has 38K+ stars on Github. Caddy is written in Go language and can be used for static resource hosting and reverse proxy. Caddy has the following main features: Compared with the complex configuration of Nginx, its original Caddyfile configuration is very simple; it can dynamically modify the configuration through the AdminAPI it provides; it supports automated HTTPS configuration by default, and can automatically apply for HTTPS certificates and configure it; it can be expanded to data Tens of thousands of sites; can be executed anywhere with no additional dependencies; written in Go language, memory safety is more guaranteed. First of all, we install it directly in CentO

Using Jetty7 for Web server processing in Java API development Using Jetty7 for Web server processing in Java API development Jun 18, 2023 am 10:42 AM

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

Real-time protection against face-blocking barrages on the web (based on machine learning) Real-time protection against face-blocking barrages on the web (based on machine learning) Jun 10, 2023 pm 01:03 PM

Face-blocking barrage means that a large number of barrages float by without blocking the person in the video, making it look like they are floating from behind the person. Machine learning has been popular for several years, but many people don’t know that these capabilities can also be run in browsers. This article introduces the practical optimization process in video barrages. At the end of the article, it lists some applicable scenarios for this solution, hoping to open it up. Some ideas. mediapipeDemo (https://google.github.io/mediapipe/) demonstrates the mainstream implementation principle of face-blocking barrage on-demand up upload. The server background calculation extracts the portrait area in the video screen, and converts it into svg storage while the client plays the video. Download svg from the server and combine it with barrage, portrait

How to configure nginx to ensure that the frps server and web share port 80 How to configure nginx to ensure that the frps server and web share port 80 Jun 03, 2023 am 08:19 AM

First of all, you will have a doubt, what is frp? Simply put, frp is an intranet penetration tool. After configuring the client, you can access the intranet through the server. Now my server has used nginx as the website, and there is only one port 80. So what should I do if the FRP server also wants to use port 80? After querying, this can be achieved by using nginx's reverse proxy. To add: frps is the server, frpc is the client. Step 1: Modify the nginx.conf configuration file in the server and add the following parameters to http{} in nginx.conf, server{listen80

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

See all articles