This article records issues and solutions I experienced when using webpack at work.
devServer configuration
- Webpack cannot lanuch default browser chrome automatically after running
yarn dev
ornpm start
, I have to inputlocalhost:3000
at the address bar manally.
- Solution: Edit
webpack.config.js
devServer: { open: true, // set it true to let webpage auto-launch port: 3000, },
- My root route is not at
localhost:3000
, it islocalhost:3000/demo/
,then, each time I start the project, it saysCannot GET /
- Solution: Edit
webpack.config.js
, addopenPage
property:devServer: { open: true, // set it true to let webpage auto-launch openPage: 'demo/', // DONOT add <code>/</code> before <code>demo/</code> port: 3000, },
- 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
- Failed to compile when using line comments (
// comment content line
) in the style fileERROR 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 shortcutCTRL + SHIFT + A
on Linux) to do/* */
block comments.
- I use
Comments