Webpack dev – server to use

What is a webpack — dev server

With vUE -cli and react-cli scaffolding, executing yarn start starts a local server. The browser visits the server and previews the code, and reloads the data when the code file is updated. This feature is called dev-server.

In Webpack, provided by webpack-dev-server.

The webpack-dev-server library starts a server. When the browser accesses the server, it uses WebSocket to connect to the browser for a long time.

And webpack-dev-server will enable Webpack to listen to native code files. When the local code file is updated and repackaged, webpack-dev-server pushes the updated module information to the browser through WebSocket. The browser uses this compilation information to get the latest code, something like this.

: Whale2: Webpack itself supports listening for file changes. Webpack-dev-server only enables listening for WebPack by default.

The Webpack-dev-server library is not complicated, but it covers a lot of stuff.

About the Webpack-dev-server library, I would like to give an in-depth introduction.

This is divided into two parts to introduce:

  1. Describes the configuration of the Webpack-dev-server property, and describes the Settings in the source code of some properties
  2. Briefly introduce the process and principle of Webpack-dev-server.

Webpack dev – server installation

Webpack cli/bin/config – yargs problem

As of this writing, the latest version of Webpack-dev-server is 3.11.2

Those who have used this version will know that [email protected] and [email protected] get an error when used together: Cannot find module ‘webpack-cli/bin/config-yargs

Personally, I think this issue is a bit official.

Install [email protected] first to check out the error.

Yarn add – D [email protected]

If you have used webpack-dev-server, you will know that the command to run webpack-dev-server is webpack-dev-server

The official NPM documentation also includes the webpack-dev-server command

The yarn start command is usually set to webpack-dev-server,

:whale: Set yarn start:dev to webpack-dev-server here. Mainly for this mistake

At this point, if nothing else happens, do YARN start:dev to execute webpack-dev-server.

However, execution will encounter that error:

The error message is that the config.yargs module in the Webpack-CLI library cannot be found. Feel there will be a lot of new learning Webpack and search ability slightly weaker friends will be stuck in this.

Whale2: [email protected] and [email protected] used for configuration

The error can be found directly in issues.

The new command is webpack serve. Now configure the new command

In this case, the yarn start command can be successfully executed. Port 8080 is enabled by default

So what’s going on here? By viewing the source code and testing [email protected] personal slightly some guesses.

Take a look at the code in the /bin/webpack-dev-server.js file module at [email protected].

/bin/webpack-dev-server.js will be the file module executed using the webpack-dev-server command

/bin/ [config/] config-yargs and /bin/ [utils/] convert-argv from the webpack-CLI library are loaded in the /bin/webpack-dev-server.js file module.

However, the code structure has been greatly changed in the version, and these two file modules have been removed, so it also led to the error.

This problem is the reason for the current iteration.

In the previous use of the [email protected] version, [email protected] and [email protected] were used

Now updated to [email protected], webpack-CLI has also received a major update: [email protected]. And the internal structure has changed dramatically.

But the new version of Webpack-dev-Server has not yet been developed, and the [email protected] code does not fix the problem.

Webpack Serve has been added to [email protected]. Webpack serve is also a recommended webpack command in the future.

The webpack-dev-server command issue was fixed at [email protected]. But at present [email protected] has only one [email protected].

There is no stable version yet

The /bin/webpack-dev-server.js file is missing from [email protected].

The command in the [email protected] document was changed to Webpack Serve. However, webpack-dev-server can still be used.

: Whale2 :: Whale2 :: Whale2: [email protected] Starting with the release, the Webpack team changed the command for dev-server to WebPack Serve. Both Webpack and Webpack-CLI have received major updates. The new version of Webpack-dev-server has not been developed yet. So for the time being, there’s a problem

The webpack serve command can be found in the [email protected] version documentation.

webpack serve

For the execution of the webpack serve command, the execution entry file is the same as the webpack command, which is /bin/index.js of the Webpack library. The Webpack-CLI library module is invoked in this file module.

Then in the webpack-cli library according to its command parameters call @webpack-cli library /serve/lib/index.js, start the webpack-dev-server in this module file. This code is new to the [email protected] version. More on this in the next article.

: Whale2 :: Whale2: webpack, webpack-cli, and webpack-dev-server cross-library calls are all based on the module path. So any minor change in the structure of a library file will result in an error like the webpack-dev-server command. However, in the new version the code has been optimized to make cross-library calls by convention names. The coupling degree is reduced as much as possible.

:whale2: @webpack-cli is a library that [email protected] relies on.

[email protected][email protected] problem

After the yarn start command is executed, a server on port 8080 is started.

But there are problems with WebSocket when used with [email protected] and [email protected]

As mentioned above, WebSocket establishes a long link with the browser and pushes information to the browser to change the browser state.

To do a test, run YARN Start and use a browser to access it.

If you update the code at this point, you will find that the browser has not synchronized the update and the browser WS window does not push data

:whale2: WS “: WebSocket data display window


Later I debug the source code and find that there is no connection to WebSocket Server at all.

I finally found the answer on Github.

The reason is the browserslist property in package.json, which can be pushed by removing it.

This is a problem at [email protected]. However, the official explanation seems to fix the problem only in [email protected].

I also tested using the [email protected] version and the bug was fixed.

Version selection

Currently [email protected] stable is only 4 months old, and there is no stable version of webpack-dev-server corresponding to the new version. So [email protected] can only be used for learning.

Use [email protected][email protected][email protected] to learn directly here.

The [email protected] property configuration is slightly different from [email protected], The [email protected] and [email protected] attribute mappings and differences are also mentioned here.

Yarn add – D [email protected]

:whale2::whale2: [email protected] Provides a comprehensive error message. When an error attribute is set, [email protected] provides a detailed message.

Webpack dev – server configuration

The webpack-dev-server property is the devServer property configured in the WebPack configuration file. The webpack-dev-server execution reads this property for configuration.

Since webpack-dev-server is only a feature for development, the configuration properties can be written in the webpack.dev.js file

const path = require('path');
const { merge } = require('webpack-merge');
const { config } = require('./config');
const common = require('./webpack.common');
// Use node.js export to export the configuration
module.exports = merge([
  common(true),
  {
    mode: 'development'.devServer: {// server host, default localhost,
      host: '127.0.0.1'.// Server port number,
      // The default is 8080
      port: 7777.// string | boolean
      // Whether to open the browser after startup
      // The default is false. If set to true, the browser will open automatically on startup
      // When it is a string, open the specified browser
      open: true.// 'chrome'

      // The page that opens by default after the browser is opened
      // string | Array
      
      // Multiple pages open when set to Array
      openPage: ' '.// ['', 'index.html'], //'index.html',

      // Enable gzip compression,
      // Default is false
      compress: true.// Enable hot update (HMR)
      // Default is false,
      / / hot update is used in webpack HotModuleReplacementPlugin
      hot: true.// Set the IP address to allow access. If set to true, no IP address is allowed to access.
      // Can also be set to an array, as with [email protected]'s allowedHosts
      // This property is equivalent to the allowedHosts property of [email protected]
      firewall: true.// Whether to set the HTTP/2 server.
      // For nodeV10 + releases there are problems with spdy
      // So if this property is set to true, HTTPS is used as the service by default
      http2: false.// // Whether to use HTTPS for secure connection
      // // Boolean or object
      // // If the value is Object, you can set the security certificate
      // // is false by default, but HTTPS is used by default when the http2 property is enabled. By default, dev-server uses HTTPS to service HTTP/2
      // https: {
      // // certificate. The certificate properties can also be set in devServer. If HTTPS is set to Boolean, the certificate properties are set at the same level as HTTPS
      // key: '',//fs.readFileSync('/path/to/server.key'),
      // cert: '',//fs.readFileSync('/path/to/server.crt'),
      // ca: '',//fs.readFileSync('/path/to/ca.pem'),
      // },


      // Server proxy configuration, the front-end request API needs to specify the address when the current back-end separation development
      // This property sets the IP address of the proxy
      / / as follows, for example, when the API request/API/user real address to http://localhost:3000/user
      / / use please refer to the website https://webpack.js.org/configuration/dev-server/#devserverproxy for details
      proxy: {
        '/api': {target: 'http://localhost:3000'./ / prefix pathRewrite properties can be set, if not set pathRewrite: / API/user real address to http://localhost:3000/api/user
          pathRewrite: {'^/api' : ' '},
          // HTTPS is set to invalid certificate
          // secure: false}},// The custom header of response added when the server returns
      headers: {
        'X-Custom-Foo': 'bar'
      },

      // Static file properties
      // This property is a summary of some properties of [email protected]
      static: {
        // The local directory to mount static files on the server
        // The default directory is the current working directory
        // Absolute addresses are recommended
        // For example, after the asset directory is set to /assets, static files in the local /assets directory are loaded to the server
        // Equivalent to the contentBase property of [email protected]
        directory: path.join(config.root),

        // An accessible virtual address mounted to the server middleware
        // For example, if set to /static, the /static prefix is required when accessing server static files
        // Equivalent to the contentBasePublicPath property of [email protected]
        publicPath: '/'.// Sets the parameters to use when hanging static files
        // Equivalent to the staticOptions property of [email protected]
        staticOptions: undefined.// Whether to join serve-index middleware. The default value is true
        // Equivalent to [email protected] // whether the static file list can be accessed in the browser.
        // Default is true. Webpack-dev-server uses serve-index middleware for this function
        // Equivalent to the serveIndex property of [email protected]
        serveIndex: true.// Whether to use the chokidar library to listen for static file changes.
        // Webpack uses file system change notifications, but sometimes this doesn't work, such as using network file systems
        // So you can set the property to use the chokidar library for polling to detect file changes.
        // This property can be set to Boolean or object type to specify polling time (milliseconds)
        // Equivalent to the watchOptions property of [email protected]
        watch: {
          poll: 3000}},// Set some properties of the WebSocket client
      client: {
          
        // Push the client log level,
        / / attribute is "none" | "error" | "warn" | "info" | "log" | "verbose"
        // For example, if error is set, WS does not push packaged warnings and messages, and WS clients print logs on the console
        // If set to None, no message will be sent if packaging fails
        // equivalent to the clientLogLevel property of [email protected]
        logging: 'verbose'.// Whether to print the packaging progress in the browser console,
        // Equivalent to the progress property at [email protected]
        progress: true.// Equivalent to the sockPath property of [email protected]
        // path: '',
        // Equivalent to the sockHost attribute of [email protected]
        // host: '',
        // Equivalent to the sockPort attribute of [email protected]
        // port: '',
      },


       public: undefined.// Attributes used by webpack-dev-middleware
      dev: {// Set the custom header information added to server Response
        // This property is used in webpack-dev-middleware
        headers: {// Add data to the response header
          'X-Dev-Header': 'X-Dev-Header'.serverSideRender: false,},// Set mimeTypes for webpack-dev-middleware
        // Equivalent to the mimeTypes attribute of [email protected]
        // Equivalent to the mimeTypes attribute of [email protected]
        mimeTypes:{

        },

        // Whether to write packing results to disk
        // Default is false
        // Equivalent to the writeToDisk attribute of [email protected]
        writeToDisk: true.// Set the directory address where the packaged files are stored. This property is set by webpack-dev-Middleware
        For example, if it is set to /public, all server information needs to be prefixed with /public
        // Equivalent to the publicPath attribute of [email protected]
        publicPath: '/'.// Set the page to which the root directory points.
        // For example localhost:8080 can be accessed directly to index.html because the default value is index.html
        // The default value is also index.html
        // Equivalent to the index attribute of [email protected]
        index: 'index.html'.// none" | "summary" | "errors-only" | "errors-warnings" | "minimal" | "normal" | "detailed" | "verbose" | boolean | The object {... }
        // Set the package file log output level, will be output in the server terminal
        // The stats attribute equivalent to [email protected]
        stats: 'minimal'.// Customize the output stream of a packaged file
        // By default, the input stream is memory
        outputFileSystem: undefined.methods: undefined.serverSideRender: undefined

      },


      / / set the compiler errors or warnings, the page will display information directly, Boolean | {}
      // Defaults to false and displays a blank page on failure
      // If set to true, error/warning overlays will be displayed for compilation failures, or if set to Object, various types of information will be displayed
      overlay: {
        warning:true.errors: true
      },

      // Whether to inject a WebSocket client. That is, whether to carry out long link communication
      // boolean | function (compilerConfig) => boolean
      // Set this property to false to disable hot, overlay, etc
      // The default value is true, and you can test it by setting it to false
      injectClient: true.// Whether to inject HMR, which is a subset of injectClient. Only hot updates are affected
      injectHot: true.// Whether to enable the automatic browser refresh function
      // This property has a lower priority than hot
      liveReload: false.// Whether to enable ZeroConf network
      bonjour: false.// Whether to redirect all 404 pages to index.html
      // boolean | object
      // When this property is set to true or object and using the HTML5 API all 404 pages are redirected to index.html
      // If the connect-history-api-fallback library is set to an object, this object will be passed to the connect-history-api-fallback library
      historyApiFallback: false.// Whether to open the page using the LAN IP address
      useLocalIp: false.// Whether to listen for the stdin.end event in Node to shut down the server
      stdin: false.// Terminate signal, listen for ['SIGINT', 'SIGTERM'] when true; Event. The event is triggered and the process is terminated
      // Currently dev-server enforces this property to be true, so false does not work.
      setupExitSignals: true./ / set the WebSocket
      // You can set the WebSocket library to use. The built-in libraries are SOckJS and WS
      // You can also customize WebSocket Server and WebSocket Client
      transportMode: {// Set the WebSocket to be used. The value is sockjs or ws
        // Sockjs library used by sockjs
        // The ws library used by ws
        // [email protected] uses WS [email protected] uses sockJS
        // Currently an error occurs when using sockjs at [email protected], and an error occurs when using WS at [email protected]
         server: 'ws'
      },

      // Customize middleware hook properties
      // Takes precedence over server internal middleware execution
      // equivalent to the before function at [email protected]
      onBeforeSetupMiddleware: (app, server, compiler) = >{
        //console.log(' I am before', compiler.options)
      },

      // The current middleware is executed after all middleware is executed internally
      // equivalent to the after function at [email protected]
      onAfterSetupMiddleware: (app, server, compiler) = >{},// dev-server provides a hook function to execute when the server is started
      onListening: (server) = > {
        // const port = server.listeningApp.address().port;
        // console.log('Listening on port:', port);}}}])Copy the code
  • Host: indicates the host address used to start the server

    Property can be set to: String

    Default value: localhost

  • Port: indicates the port number used to start the server

    Property can be set to: Number

    Default value: 8080

  • Open: Whether the browser is automatically opened after the server is started.

    Property can be String or Boolean

    Property value: Boolean: Indicates whether to open the default browser

    Property value: String: opens the specified browser, such as Chrome

    Default value: false

  • OpenPage: route address for automatically opening the browser.

    The value can be String or Array

    The property value is String: opens the specified address

    Property value is Array: opens all addresses in the Array.

    Default value: index.html

  • Compress: Indicates whether to enable gzip compression.

    Compression using compression middleware.

    Default value: false

  • Hot: Indicates whether to enable hot update (HMR).

    Hot update (HMR) is a technique in which the browser loads only the data that needs to be updated after the code is updated. The hot update (HMR) property is one of the required properties.

    Hot update (HMR) real execution is HotModuleReplacementPlugin webpack

    Default value: false

  • Firewall: indicates whether to enable the firewall

    The value can be Boolean or Array

    The value of the attribute is Boolean: Whether to enable the firewall. If the value is true, no other hosts are allowed to access the firewall. If the value is false, other hosts are allowed to access it

    The value is Array: sets the accessible IP address. Equivalent to allowedHosts in [email protected]

    Default value: true

    : Whale2: This property is the allowedHosts property of [email protected]

  • HTTPS: specifies whether to use the HTTPS secure connection mode.

    Property Can be Boolean or Object

    The value of the attribute is Boolean: Specifies whether HTTPS is used for connection

    If the value is Object, the HTTPS security certificate information is set

    Default value: false

  • Http2: whether to use HTTP/2

    When this property is set to true, the HTTPS secure connection is used by default. So HTTPS will be set to true

    Default value: false.

  • Proxy: indicates the server proxy configuration.

    When the front end is separated from the front end, the front end request API needs to specify an address. This property can configure an IP address. When accessing the specified request, the configured IP address will be requested.

    For example, visit http://localhost:3000 when requesting/API interfaces. Specific reference website: [devserverproxy] (https://webpack.js.org/configuration/dev-server/#devserverproxy).

    Alternatively, you can skip this property and use a static string or configuration file. Look at personal coding habits

  • Headers: Sets the user-defined header information in the Response message of the server.

    Property can be set to Object

    Default value: null

  • Static: Indicates the configuration of static file properties

    The value can be Object or Array

    If the property value is Object, static file properties are configured

    Property value: Array: Configures multiple static file properties

    [email protected] does not have this property. This property simply encapsulates the properties in [email protected] about static file configuration

    • Directory: Sets the local directory where the server is mounted to a static file.

      For example, after the asset is set to /assets, static files in the local /assets directory are loaded to the server

      Property can be set to: String

      Default value: / package.json File address.

      :whale2: This property is the contentBase property of [email protected]

    • PublicPath: the virtual address to which static files are mounted to the server.

      For example, if set to /static, static files must be prefixed with /static

      Property can be set to: String

      Default value: /

      :whale2: This property is the contentBasePublicPath property of [email protected]

    • StaticOptions: parameter used when the server mounts static files

      Webpack-dev-server mounts static files using express.static(Directory,staticOptions) middleware, This property is used by express.static(Directory,staticOptions). For details, see the Express framework

      Property can be set to Object

    • ServeIndex: Whether the list of static files can be accessed in the browser.

      Webpack-dev-server uses the serve-index library as a browser to access static files.

      Property can be set to: Boolean

      Default value: true

      :whale2: This property is the serveIndex property of [email protected]

    • Watch: Whether to use polling to check file changes.

      Webpack uses file system change notifications by default. However, in special cases, such as network file systems, message notifications fail

      So you can use polling to check for file changes. Use Chokidar to do polling detection

      Property Can be Boolean or Object

      The value of the attribute is Boolean: Indicates whether polling detection is enabled

      If the value is Object, polling parameters, such as polling time, are configured

      Default value: false

      : Whale2: This property is the watchOptions property of [email protected]

    • Client: Indicates the setting of WebSocket client properties.

      Property can be set to Object

      [email protected] does not have this property. This property simply encapsulates the summary of WebSocket client configuration properties in [email protected]

      • Logging: The WebSocket client outputs log levels in the browser console.

        Property can be set to “none” | “error” | “warn” | “info” | “log” | “verbose”

        Default value: info

        Verbose, for example, outputs all logs to the browser console. None prints no logs

        :whale2: This property is the clientLogLevel property of [email protected]

      • Progress: Whether to output the packaging progress in the browser console (whether to display the packaging progress in the browser console)

        Property can be set to: Boolean

        Default value: false

        :whale2: This property is the progress property of [email protected]

    • Dev: Sets some configuration properties used by the Webpack-dev-Middleware middleware.

      Property can be set to Object

      [email protected] does not have this property. This property simply encapsulates the summary of webpack-dev-Middleware use properties in [email protected]

      • Headers: Sets the user-defined header information in the Response message of the server.

        Devserver. headers is used in [email protected] in two places. [email protected] is split, and this property is only responsible for webpack-dev-middleware. It just all came out the same.

        Property can be set to Object

      • MimeTypes: Sets the webpack-dev-middleware mimeTypes property, as described in the Webpack-dev-middleware documentation.

        : Whale2: This property is the mimeTypes property of [email protected]

      • WriteToDisk: Indicates whether to write the packaged compiled file to the disk

        Webpack-dev-middleware writes packaged compilation files to the memory stream by default for faster access.

        Property can be set to: Boolean

        Default value: false

        :whale2: This property is the writeToDisk property of [email protected]

      • PublicPath: sets the address of the directory where the packaged and compiled files are stored

        For example, if it is set to /public, the /public prefix must be added whenever accessing the file resources generated by the packaged compilation

        Property can be set to: String

        Default value: /

        :whale2::whale2: static. PublicPath is different from dev.publicPath

        PublicPath represents the address of static files stored on the server. Code using static files needs to add a directory prefix

        Dev. PublicPath represents the address of the directory where the code is compiled and packaged. The directory prefix is required for browser access

        :whale2: This property is the publicPath property of

      • Index: indicates the file pointed to by the root directory.

        This property is why you can point to index.html in the browser’s access root directory.

        Property can be set to: String

        Default value: index.html

        :whale2: This property is the index property of [email protected]

      • Stats: Sets the log output level when packaging files.

        When you start dev-Server, you see a lot of packaging information in the console: file size, file name, and so on, which is controlled using this property.

        Properties can be set to: “None” | “summary” | “errors – the only” | “errors, warnings minimal” | “” |” normal “|” detailed “|” verbose “| Boolean | The object {… }

        Default value: Normal

        :whale2: This property is the stats property of [email protected]

      • OutputFileSystem: Controls the output stream of a packaged file.

        The default output stream is the memory stream, which packages the file compilation into memory. This property can change the output stream.

  • Overlay: Whether to display errors/warnings directly on the page during compilation.

    This property is buggy at [email protected].

    Property Can be Boolean or Object

    Property value: Boolean: false does not display; When true, it is displayed on the page when compilation errors occur

    Attribute value Object: custom configuration warning and error status.

  • InjectClient: Whether to inject WebSocket

    Properties can be set to Boolean, function (compilerConfig) => Boolean

    Default value: true

  • InjectHot: whether to injectHot update (HMR).

    This property is equivalent to a subset of the injectClient property and only controls hot updates (HMR)

    Properties can be set to Boolean, function (compilerConfig) => Boolean

    Default value: true

    : Whale2 :: Whale2: This property can also be set to the only string in the [email protected] source code, which is the hotOnly property in [email protected]. However, only Boolean is allowed in property validation.

  • LiveReload: Whether to start the refresh browser

    This property, when enabled, will refresh the browser after updating code data

    However, this attribute has a lower priority than hot. After hot update is enabled, hot update takes precedence over hot update.

    Property can be set to: Boolean

    Default value: false

  • Bonjour: Whether to enable the Zeroconf network

    For Zeroconf, check out the documentation

    Property can be set to: Boolean

    Default value: false

  • HistoryApiFallback: Whether to point all 404 pages to index.html

    This property uses connect-history-api-fallback to handle 404 pages

    Property Can be Boolean or Object

    Attribute value: Boolean: Indicates whether this function is enabled

    Object: sets the connect-history-api-fallback library parameters

    Default value: false

  • UseLocalIp: specifies whether to enable the server using the local LAN

    Property can be set to: Boolean

    Default value: false

  • Stdin: Whether to listen for the stdin.end event in Node.js to shut down the server

    Property can be set to: Boolean

    Default value: false

  • SetupExitSignals: Whether to listen for [‘SIGINT’, ‘SIGTERM’] events in Node.js to shut down the server.

    This property is a new addition to [email protected]. In the test at [email protected], this property has a built-in true property and cannot be changed

  • TransportMode: Sets the WebSocket library information.

    Webpack-dev-server has two built-in WebSocket libraries: WS and SOckJS. WebSocket Server and WebSocket Client can be customized. Please refer to the official website for details

    :whale2:

    [email protected] The default value is ws

    [email protected] The default value is sockjs

    • OnBeforeSetupMiddleware: Custom hook middleware function that takes precedence over other middleware.

      :whale2: This property is the before property of [email protected]

    • OnAfterSetupMiddleware: Custom hook middleware function that executes after all middleware.

      : Whale2: This property is the after property of [email protected]

    • OnListening: Sets the hook function to be executed after the webpack-dev-server is started.

These are some of the configuration properties in [email protected].

The [email protected] version has better integration of configuration properties than [email protected].

host / port

These two properties are among the easiest to understand and most commonly used.

Webpack-dev-server uses the Express framework internally.

The /lib/server. js file in [email protected] is the webpack-dev-server Server module.

/lib/server.js has a listen(), which starts the Server function.

And listen () call is in @ webpack – serve/lib/cli library startDevServer. Js.

Can see in the serve/lib/startDevServer. Js. Use the options in the port and the options. The host attribute value to start the server.

These two properties are devServer from the WebPack configuration.

The default 8080 port number is provided in findPort().


The source code for: Whale2 :: Whale2: is based at [email protected]

Open, openPath

These two properties determine whether to start the browser after the server starts.

The server.listen () callback calls showStatus().

The /lib/util/ runopen.js module is then called to launch the browser

As you can see, both the Open and openPath attributes are typed.

The open property supports setting a string to open a specified browser;

OpenPath can be configured to open multiple tabs for arrays. Finally, the open library is used to open the browser

Hot, lveReload

The hot attribute is used in the server.listen () callback, and WebSocket· Server is created when the hot or liveReload attribute is set.

If hot or liveReload is set, WebSocket will be used for long links to the browser

static

The static attribute, as mentioned earlier, is [email protected]’s encapsulation of attributes about static files: access paths, file listeners, and so on.

Only some of the attributes are described in detail here.

Directory, publicPath, staticOptions

These three properties are used by the Express server to set up static files.

In the Server. SetupStaticFeature (), use the express Server mount the static file middleware (express. Static).

The access address to mount the middleware to the server is static.publicPath.

The address of the mounted static file is static.directory.

You can see that the Express server has mounted its access directory as publicPath. The local static file directory to be mounted is directory.

Static file middleware uses the parameter static.staticoptions

For example,

Set the static.directory property to: path.join(config.root, ‘assets’); Static. Set the publicPath property to /static

When accessing /assets/images/yj.png, you should use /static/images/yj.png



:whale2::whale2: static. PublicPath and static. Directory attributes are not customizable

:whale2: The static and static.publicPath attributes in the source code are both arrays. Therefore, you can set the properties to Array

: Whale2: This is just an example of images, not file packaging.

serveIndex

This property sets whether static files can be viewed in the browser. Webpack-dev-server uses the serve-index library internally

If the static.serverIndex property is set to false, the static file path will be 404 when viewed in a browser


If the static.serverIndex property is true, static files can be viewed in the browser


dev

This property is a collection of properties used by the Webpack-dev-Middleware library.

index

This property is set file, the root points to code in webpack dev – middleware in the library/dist/utils/getFilenameFromUrl js file

As you can see, a type judgment is made when handling the static.index property.

And the default value is index.html.

Since the filename attribute in the HTml-webpack-plugin library defaults to index.html as well

This allows code to be accessed in the root directory by default without configuration.

You can also change this property. However, change the FILENAME attribute of the HTML-webpack-plugin library when you change the code. Otherwise, 404 will be accessed


: Whale2 :: Whale2 :: Whale2: Conventions are greater than configurations. Use conventions when writing code.

stats

This property controls the level of packaged log output. By default, webpack-dev-server is executed. Always output a lot of logs on the console. The log information is controlled by this attribute.

The code is in the /dist/utils/ setuphook. js module in the Webpack-dev-Middleware library.

The stats field in the code is an internally supplied state object that retrieves the specified state information based on the statsOptions (dev.stats) property.

If you set dev.stats to errors-only, the console would not have so many logs, and the errors-only attribute value means that logs are only printed if code packaging errors occur.

If set to None, the error log is no longer printed. .

overlay

This property controls whether an error message is displayed on the page when warnings and errors occur while the code is packaged and compiled.

This property is buggy in version [email protected].

You can see the clientOverlay attribute used in the server.js file below, but not in the dev object.

You need to change the source code during testing. Change clientOverlay to Overlay.

So you need to change the source code during testing. Change clientOverlay to Overlay.

When the overlay attribute is true, error messages are displayed directly on the page if the code has a compilation error.

This function personally feels quite good to use. However, some people may prefer to use the console to view error information, namely the dev.stats attribute.

historyApiFallback

This property represents whether all invalid routes (404) are redirected to the specified page when using the HTML5 API.

Similar to a project that directs all invalid routes (404) to a specified 404 page

Webpack-dev-server uses the connect-history-api-Fallback middleware internally to do the processing. The default redirect page is index.html.


conclusion

:whale2::whale2::whale2:

  • Webpack-dev-server is a feature provided for ease of development that uses WebSocket to establish long links to the server.
  • [email protected] version made extensive changes to the code structure, resulting in [email protected]webpack-dev-serverThe command will report an error.
  • The [email protected] version provides a better summary of devServer properties by function.

If this article is helpful to you, ask for a star here. Project address: OrcasTeam/my-cli

In this paper, the reference

  • Webpack website
  • webpack-dev-server
  • webpack-cli

This article rely on

package.json

{
  "name": "my-cli"."version": "1.0.0"."main": "index.js"."author": "mowenjinzhao<[email protected]>"."license": "MIT"."devDependencies": {
    "@babel/core": "7.13.1"."@babel/plugin-transform-runtime": "7.13.7"."@babel/preset-env": "7.13.5"."@babel/preset-react": "7.12.13"."@babel/runtime-corejs3": "7.13.7"."babel-loader": "8.2.2"."clean-webpack-plugin": "3.0.0"."html-webpack-plugin": "5.2.0"."webpack": "5.24.0"."webpack-cli": "4.5.0"."webpack-dev-server": "4.0.0 - beta. 0"."webpack-merge": "5.7.3"
  },
  "dependencies": {
    "react": "17.0.1"."react-dom": "17.0.1"
  },
  "scripts": {
    "start:dev": "webpack-dev-server --config build/webpack.dev.js"."start": "webpack serve --config build/webpack.dev.js"."build": "webpack --config build/webpack.pro.js",},"browserslist": {
    "development": [
      "chrome > 75"]."production": [
      "ie 9"]}}Copy the code