Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to set up webpack 5 from scratch

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to set up webpack 5 from scratch". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to set up webpack 5 from scratch.

If you are upgrading from webpack 4 to webpack 5, here are some considerations:

The webpack-dev-server command is now replaced by webpack-serve

File-loader, raw-loader, and url-loader are not required, you can use the built-in Asset Modules

The node polyfill is no longer available, for example, if you encounter a stream error, you can add the stream-browserify package as a dependency and add {stream:'stream-browserify'} to the alias attribute in the webpack configuration.

What is webpack?

Nowadays, most websites are no longer just written in native JS+ pure HTML, but also involve languages that browsers cannot understand. If the project is large and there are many files, the corresponding volume will be large. So to compress the file and translate it into something that all browsers can understand, this is the opportunity for webpack to use its talents.

Webpack can be thought of as a module baler: what it does is analyze your project structure, find JavaScript modules and other extension languages (Scss,TypeScript, etc.) that browsers can't run directly, and package them into an appropriate format for browsers to use.

For development, webpack also provides a development server that dynamically updates modules and styles as we save them. Both vue create and create-response-app are essentially dependent on webpack.

Webpac k can do a lot of things, and this article is just to help you familiarize yourself with some major concepts and do some manual configuration.

Installation

First, create a directory webpack-tutorial with the following commands:

Mkdir webpack-tutorial cd webpack-tutorial npm init-y / / create a default package.json

Install webpack and webpack-cli:

Npm I-D webpack webpack-cli

Next, create the directory src and create an index.js in it, as follows:

Console.log ('Interactive')

Basic configuration

Create a webpack.config.js in the root directory of the project.

Entry

Entry is the entry of the configuration module, which can be abstracted into input. The first step of Webpack performing the build will search from the entry and recursively parse out all the modules on which the entry depends.

Entry configuration is required. If left empty, it will cause Webpack to exit with an error. Here, we use src/index.js as the entry point.

Const path = require ('path') module.exports = {entry: {main: path.resolve (_ _ dirname,'. / src/index.js'),},}

Output

Configure the output option to control how webpack writes compiled files to the hard disk. Note that even though there can be multiple entry starting points, only one output configuration is specified. Here the output path is specified as' dist':

Module.exports = {/ *... * / output: {path: path.resolve (_ _ dirname,'. / dist'), filename:'[name] .bundle.js',},}

We now have the minimum configuration required to build the bundle. In package.json, we can create a build script that runs the webpack command.

"scripts": {"build": "webpack"}

Now you can run it:

Npm run build

Now a main.bundle.js file will be generated in the dist directory

Plug-in

Webpack has a plug-in interface, which makes it more flexible. Internal webpack code and third-party extensions use plug-ins, and there are some major methods that almost every webpack project uses.

HTML template file

Currently, we have a random bundle file, but it is not very useful to us yet. If you need to use main.bundle.js, use the HTML page to load the JS package as a script. We want the HTML file to automatically introduce this generated js file, so we will use html-webpack-plugin to create a HTML template.

Install:

Npm I-D html-webpack-plugin

Create a template.html file in the src folder. Here, we customize a title with the following contents:

Src/template.html

Create the plugins attribute of the configuration, then add the plug-in, file name to the output (index.html), and link to the template file that will be based on the template.

Const path = require ('path') const HtmlWebpackPlugin = require (' html-webpack-plugin') module.exports = {/ *... * / plugins: [new HtmlWebpackPlugin ({title: 'webpack Boilerplate', template: path.resolve (_ _ dirname,'. / src/template.html'), / / template file filename: 'index.html', / / output file}),],}

Now run the build again, and you'll see that the dist folder now contains an index.html, and our packaged js file is automatically introduced. Open index.html with a browser and you will see Interesting! in the console.

Then, in index.js, we dynamically insert some dom elements into the page, as follows:

/ / Create heading node const heading = document.createElement ('H2') heading.textContent = 'interestingships' / / Append heading node to the DOM const app = document.querySelector ('# root') app.append (heading)

Rebuild, under the dist directory, run the html file with http-server.

Http-server

You can see on the page that we injected "Interesting!" and notice that the bundled file has shrunk.

Note: after installing HtmlWebpackPlugin, you will see a DeprecationWarning, because the plug-in has not completely got rid of the deprecation warning after upgrading to webpack 5.

Clean

We also need to set up clean-webpack-plugin to clear everything in the dist folder after each build. This is important to ensure that no old data is left behind.

Clean-webpack-plugin- delete / clean up the build folder

Const path = require ('path') const HtmlWebpackPlugin = require (' html-webpack-plugin') const {CleanWebpackPlugin} = require ('clean-webpack-plugin') module.exports = {/ *... * / plugins: [/ *... * / new CleanWebpackPlugin (),],}

Modules and Loaders

Webpack uses loader to preprocess loaded files such as js files, static resources (such as images and CSS styles), and compilers (such as TypeScript and Babel). Webpack 5 also has some built-in asset loaders.

In our project, there is a HTML file that loads and introduces some JS, but nothing is actually done. So what is the main thing to do with this webpack configuration?

Compile JS into a version that the browser can understand

Import styles and compile SCSS to CSS

Import images and fonts

(optional) set React or Vue

Babel (JavaScript)

Babel is a tool that lets you use the latest JS syntax.

Establish a rule to check any .js file in the project (outside of node_modules) and convert it using babel-loader. Babel has some other dependencies:

Babel-loader- uses Babel and webpack to transfer files.

@ babel/core- converts ES2015+ to backward compatible JavaScript

Smart default settings for @ babel/preset-env-Babel

@ babel/plugin-proposal-class-properties- example of a custom Babel configuration (using properties directly on a class)

Npm I-D babel-loader @ babel/core @ babel/preset-env @ babel/preset-env @ babel/plugin-proposal-class-properties

Webpack.config.js

Module.exports = {/ *... * / module: {rules: [/ / JavaScript {test: /\ .js $/, exclude: / node_modules/, use: ['babel-loader'],},],},}

In the case of a TypeScript project, use typescript-loader instead of babel-loader.

Babel is now set up, but our Babel plug-in is not available yet. You can add some new syntax to index.js to prove that it doesn't work yet.

/ / create a class attribute class Game {name = 'Violin Charades'} const myGame = new Game () / create p node const p = document.createElement (' p') p.textContent = `I like ${myGame.name}. `const heading = document.createElement ('h2') heading.textContent =' interestingkeeper' Const app = document.querySelector ('# root') app.append (heading, p)

To solve this problem, simply create a .babelrc file in the root directory of the project. You can use preset-env and plugin-proposal-class-properties to add more default values.

{"presets": ["@ babel/preset-env"], "plugins": ["@ babel/plugin-proposal-class-properties"]}

Images

Suppose we need to reference a picture and import it directly into the JS file, which will not work properly. To demonstrate, create a src/ images, add an image to it, and then try to import it into an index.js file.

Src/index.js

Import example from'. / images/example.png' / *.

When you run the build, you see the error again:

Webpack has some built-in asset modules that can be used for static resources. For image types, we will use asset/resource. Note that this is a type, not a loader.

Webpack.config.js

Module.exports = {/ *... * / module: {rules: [/ / Images {test: /\. (?: ico | gif | png | jpg | jpeg) $/ I, type: 'asset/resource',},],},}

After building, you can view it in the dist folder.

Font and inline

Webpack also has an asset module, and you can use asset/inline to inline some data, such as svgs and fonts.

Src/index.js

Import example from'. / images/example.svg' / *.

Webpack.config.js

Module.exports = {/ *... * / module: {rules: [/ / Fonts and SVGs {test: /\. (woff (2)? | eot | ttf | otf | svg |) $/, type: 'asset/inline',},],},}

Styles

Similarly, you need to use style loader to perform operations similar to import 'file.css' in a script.

Many people are now using CSS-in-JS, styled-components, and other tools to introduce styles into their JS applications.

When the site has only one CSS file, it is sufficient to be able to load only one CSS file. But if you want to use PostCSS, in order to be able to use all the latest CSS features in any browser. Or if you want to use Sass or CSS preprocessors, you need to use other loader processing.

I want to use these three methods-- writing in Sass, processing in PostCSS, and compiling to CSS. This requires the introduction of some loaders and dependencies.

Sass-loader-load SCSS and compile to CSS

Node-sass-Node Sass

Postcss-loader-use PostCSS to process CSS

Css-loader-parsing css import

Style-loader-injecting CSS into DOM

Npm I-D sass-loader postcss-loader css-loader style-loader postcss-preset-env node-sass

Just like Babel, PostCSS needs a configuration file, postcss.config.js, create it in the root directory and enter the following:

Postcss.config.js

Module.exports = {plugins: {'postcss-preset-env': {browsers:' last 2 versions',},},}

To test whether Sass and PostCSS are working properly, create a src/styles/main.scss and enter the following:

Src/styles/main.scss

$font-size: 1rem. $font-color: lch (53 105 40); html {font-size: $font-size; color: $font-color;}

Now, import the file into index.js and add four loader. They compile from last to the first, so the last one in the list is sass-loader, because you need to compile, then PostCSS, then CSS, and finally style-loader, which injects CSS into DOM.

Src/index.js

Import'. / styles/main.scss' / *.

Webpack.config.js

Module.exports = {/ *... * / module: {rules: [/ / CSS, PostCSS, and Sass {test: /\. (scss | css) $/, use: ['style-loader',' css-loader', 'postcss-loader',' sass-loader'],},],},}

Now, at the time of rebuilding, Sass and PostCSS have been applied to the project.

Development

Run npm run build every time you update, and the larger the site, the longer it takes to build, which is very cumbersome. To do this, you can set two configurations for webpack:

Production configuration to minimize, optimize, and delete all source mappings

Development configuration, which runs webpack on the server, is updated with each change, and has a source mapping

In development mode, instead of building a dist file, you need to install webpack-dev-server to run everything in memory

Npm I-D webpack-dev-server

For demonstration purposes, we can just add the development configuration to the current webpack.config.js file we are building and test it. However, we generally need to create two configuration files for development: mode: production for the production environment and mode: development for the development environment.

Const webpack = require ('webpack') module.exports = {/ *... * / mode:' development', devServer: {historyApiFallback: true, contentBase: path.resolve (_ _ dirname,'. / dist'), open: true, compress: true, hot: true, port: 8080,} Plugins: [/ *... * / / Only update what has changed on hot reload new webpack.HotModuleReplacementPlugin (),],})

We add mode: development and create the devServer attribute, where the default port will be 8080, automatically opens the browser window, and uses hot-module-placement, which requires the webpack.HotModuleReplacementPlugin plug-in. This way the module performs updates without completely reloading the page-so if you update some styles, those styles will change and you don't have to reload the entire JS, greatly speeding up development.

You can now use the webpack serve command to start the project.

Package.json

"scripts": {"start": "webpack serve"} npm start

When you run this command, a link to localhost:8080 automatically pops up in the browser. You can now update Sass and JavaScript and watch their dynamic updates.

At this point, I believe you have a deeper understanding of "how to set up webpack 5 from scratch". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report