A note-taking of using Webpack 5.x

2021年04月22日 1304Browse 0Like 0Comments

This article records issues and solutions I experienced when using webpack at work.

devServer configuration

  1. Webpack cannot lanuch default browser chrome automatically after running yarn dev or npm start, I have to input localhost:3000 at the address bar manally.
  • Solution: Edit webpack.config.js
      devServer: {
        open: true, // set it true to let webpage auto-launch
        port: 3000,
      },
    
  1. My root route is not at localhost:3000, it is localhost:3000/demo/,then, each time I start the project, it says Cannot GET /
  • Solution: Edit webpack.config.js, add openPage property:
      devServer: {
        open: true, // set it true to let webpage auto-launch
        openPage: 'demo/',   // DONOT add <code>/</code> before <code>demo/</code>
        port: 3000,
      },
    
  1. Get 404 Not found error when refreshing non-root route page manually.
  • Reason: This is because the SPA uses client-side rendering and programming router navigation (inside the application, a route is a usually a component), and there is no request sending to the server when navigation inside the SPA. However, a manual refresh of non-root will send a request to the server, but no resource will be returned as the server-side rendering does except the root route request.

  • Solution: As I use history style router(provided by react-router-dom), and the historyApiFallback configuration item of webpack is used for fixing this issue.

      devServer: {
        historyApiFallback: {
          index: '/demo/',
          // other configurations
        },
      },
    

    or:

      devServer: {
        historyApiFallback: {
          rewrites: [
            {
              from: /^.*/g,
              to: '/demo/',
            },
          ],
        },
       // other configurations
      },
    

  • Note: I found historyApiFallback: true doesn't work for me, this may be caused by I don't serve my devlopment env at / instead of /demo. By doing the above(both ways works):

    • a non-existing route will fallback to root route automatically;
    • programming routes can be put in the browser address bar and access them directly.

assets loaders

  1. Failed to compile when using line comments (// comment content line) in the style file
    	ERROR in ./src/index.scss
    	Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
    	ModuleBuildError: Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
    	Error: Unexpected '/'. Escaping special characters with \ may help.
    
  • Solution: Just use block comments only(/* line or block comments */) instead of line comments(//).
    • I use CTRL + / shortcut to comment out/uncomment code at the beginning of each line
    • use CTRL + SHIFT + /(I changed the default shortcut CTRL + SHIFT + A on Linux) to do /* */ block comments.

Sunflower

Stay hungry stay foolish

Comments