Introduction to the

According to webPack’s official website, WebPack is essentially a static Module bundler for javascript applications, which packages modules according to dependencies and rules into front-end resources suitable for production deployment. Webpack can asynchronously load references on demand by module, and any resource can be treated as a module through loader conversion, such as CSS, images, JSON, CommonJS module, AMD module, ES6 module, etc. Now that the big version of Webpack has been updated to 4.x, let’s take a look at how it works.

1. Installation and use

Create a new folder and do the following:

npm init
npm i webpack webpack-cli webpack-server -D
Copy the code

Start using WebPack. Create folders SRC, dist and webpack.config.js in the folder, where SRC is the packaged source directory for storing the files we want to package, dist is the output directory, webpack.config.js is the file for configuring webpack packing parameters.

  • Project directory

  • webpack.config.js
//webpack.config.js
const path = require('path')

module.exports = {
  // Package mode, optional development and production
  mode: 'development'.// Configure the entry file
  entry: './src/index.js'.// Configure the output file
  output: {
    // Output path
    path: path.resolve(__dirname, './dist'),
    // Output the file name
    filename: 'build.js'
  },
  // module, you can use various loaders, such as CSS conversion, image compression, etc
  module: {},
  // plugins for template generation and other functions
  plugins: [],
  // You can configure the local WebPack development service function
  devServer: {}
}
Copy the code

Once you’ve written webpack.config.js, use the command NPX webpack to start packing. If you need to package images, CSS, fonts, SVG and other resources, you must use ES6 or CommonJS module loading specification to introduce the import file, otherwise there is no packaging build.

  • Module and some loader usage

Module can use loader to process imported modules. The supported module types are CoffeeScript, TypeScript, ES5/6, Sass, less, stylus. Modules depend on:

1.ES2015 importstatements
2. CommonJS require()statements
3. AMD definerequirestatements
4. In CSS /sass/ LESS files@importstatements
Styles 5.(url(...) )Or HTML file(<img src=... >)Image link in(image url)

Install the loader(NPM I xxx-loader-d) to install the loader(NPM I xxx-loader -d).

// webpack.config.js
module.exports = {
  mode: ' '.entry: ' '.output: {},
  module: {
    rules: [{test: /\.css$/.// Matches the CSS file module
        use: ['style-loader'.'css-loader'] // Use the corresponding loader
      },
      {
        test: /\.(png|gif|jpe? g|svg)$/.// Match image files
        use: [{
          loader: 'file-loader'.options: {
            name: '[path][name].[ext]? [hash]'.// outputs something like the following
            // path/to/file.png? e43b20c069c4a01867c31e98cbce33c9}}}, {test: /\.(html)$/.// To match the HTML file module. , you can package image resources introduced in HTML tags
        use: [{
          loader: 'html-loader'.options: {
            attrs: ['<tag>:<attribute>'] // 
      
        is the tag name of the imported image, and 
       
         is the attribute name of the imported image
       
      }}]}]},plugins: [].devServer: {}}Copy the code

Through the use of several loaders in the above example, the function and usage of the module are roughly introduced. If you don’t have the features you need, look for them on the Webpack website.

There is also an image packaging url-loader, which needs to be paid attention to the difference between it and file-loader. Url-loader is a further encapsulation of file-loader and can convert images to Base64 format inline in code, thus reducing HTTP requests for image loading.

  • Use of plugins

Plugins are also an important feature of WebPack, enabling you to do things that loader cannot do. To use the plug-in, you also need to use the NPM installation (NPM I xxx-d) and reference the plug-in in webpack.config.js. I’ll briefly introduce the use of a few plugins. For more complete information, visit the WebPack plugin.

// webpack.config.js
const path = require('path')
// You need to load the plugin before using it
const CleanWebpackPlugin = require('clear-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
  mode: ' '.entry: {
    a: './src/a.js'.// Multiple entry files can be imported
    b: './src/b.js'
  },
  output: {
    path: path.resolve(__dirname + '/dist/'),
    filename: '[name].[hash:8].js' // Output multiple results with hash names
  },
  module: {},
  plugins: [
    // Clean up the dist directory after each build
    new CleanWebpackPlugin(['dist']),
    // Generate HTML files to the input directory
    new HtmlWebpackPlugin({
      // You can use HTML source files in the SRC directory as templates
      template: './src/index.html'.// Generate the target file in the target directory
      filename: './dist/index.html'.chunks: ['a'.'b'] // This argument, along with entry, loads the packaged module into an HTML file as 
    }),
    // This plug-in can copy files from the source directory directly to the destination directory
    new CopyWebpackplugin([{
      from: './src/*.css'.// Select all CSS files in the source directory
      flatten: true // Select copy files or include folders. Default is false}])],devServer: {}}Copy the code
  • devServer

DevServer can set up a WebPack build service environment locally

// webpack.config.js
module.exports = {
  mode: ' '.entry: {},
  output: {},
  module: {},
  plugins: [].devServer: {
    contentBase: '/dist'.// The content directory of the service
    port: 4396.// The port number of the local service
    compress: true.// The service enables gzip compression
    open: true // Automatically open the local browser}}Copy the code

Also rewrite package.json in the project directory.

// package.json
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"."start": "webpack-dev-server".// Start the local WebPack development service environment
  "build": "webpack" // Perform packaging
}
Copy the code

Then we can execute NPM run start, NPM run webpack to start the service and perform the packaging.

2. Multiple file entry packages

The essence of multi-file packaging is to add multiple package entries to the entry entry. HtmlWebpackPlugins used two of these entries to introduce plugins above. We naturally think of how many entry files there are, and just add a few entries to the entry. Although this can achieve multi-file packaging, but every time we add a new entry has to manually add, very troublesome. So we try to match all the entry files in the source directory and then add them to entry.

function getEntry () {
  let globPath = 'src/**/*.html' // Matches the HTML files in all folders in the SRC directory
  / / (\ | \ \ \ \) this kind of writing is to compatible with Windows and MAC system directory path different writing
  let pathDir = 'src(\/|\\\\)(.*?) (\ / | \ \ \ \ ' // The paths are all folders in the SRC directory
  let files = glob.sync(globPath)
  let dirname, entries = []
  for (let i = 0; i < files.length; i++) {
    dirname = path.dirname(files[i])
    entries.push(dirname.replace(new RegExp(A '^' + pathDir), '$2').replace('src/'.' '))}return entries
}

function addEntry () {
  let entryObj = {}
  getEntry().forEach(item= > {
    entryObj[item] = resolve(__dirname, 'src', item, 'index.js')})return entryObj
}
Copy the code

Using the above two methods we can get all the entry files in the SRC directory. How to change webpack.config.js

// ...
{
  // entry: resolve(__dirname, "src/home/index.js")
  / / to
  entry: addEntry()
  / /...
}
// ...

getEntry().forEach(pathname= > {
  let conf = {
    filename: pathname.replace('src/'.' ') + '.html'.template: path.join(__dirname, 'src', pathname, 'index.html'),
    chunks: Array.call([], pathname)
  }
  webpackconfig.plugins.push(new HtmlWebpackPlugin(conf))
})
Copy the code

In this way, we can achieve automatic matching of all entry files and HTML template files to generate, at the same time in the use of HtmlWebpackPlugin, also automatically added a number of template entry, in the target directory to generate multiple HTML files.

The above is just a general introduction to the idea of multiple entry, specific code can see my implementation of a demo multi-page packaging

Refer to the article

Webpack document

Webpack4. x Getting started Configuration

Webpack multi-entry file page packaging configuration

Webpack front-end multi-page project engineering

The original link: tech.gtxlab.com/webpack4.ht…


About the author: Gong Chenguang, Renhe front-end engineer of future big data.