Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Some time ago, I used Webpack 5 to build a React and typescript scaffolding to serve as the basic scaffolding for the company’s projects. However, I encountered many problems in actual use, which need to be summarized and recorded.

Here’s how I built the React+TS generic Webpack scaffolding (Stage 1)

Here’s how I built the React+TS generic Webpack scaffolding (Phase 2)

1, BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.

The error message

X #### solution is added to webpack.base.config.js

module.exports = { resolve: { alias: { crypto: false, stream: false, assert: false, http: false, https: False}}} // Specify which one to add according to the error messageCopy the code

2, Can’t resolve ‘react/jsx-runtime’ in ‘./node_modules/ XXX ‘

The error message

Can't resolve 'react/jsx-runtime' in './node_modules/xxx'
Copy the code

The solution

Add to webpack.base.config.js

module.exports = {
    resolve: {
	alias: {
            //...
            'react/jsx-runtime': require.resolve('react/jsx-runtime')
	}
    }
}
Copy the code

3, Process is not defined webpack

The error message

process is not defined webpack
Copy the code

The solution

Because webpack 5 no longer for the Node. Js variable contains polyfill, to avoid using relevant API on the front end, documentation: webpack.js.org/migrate/5/#…

Therefore, this error occurs when you encounter dependent packages with fields such as Process. Many answers will give you an answer yes

//webpack.base.config.js

module.exports = {
    plugins: [ 
        //...
        new webpack.ProvidePlugin({ 
            process: 'process/browser', 
        }), 
    ],
}    
Copy the code

But this will result in a new error:

Cannot find module "process/browser"
Copy the code

So the correct answer is:

module.exports = {
    plugins: [ 
        //...
        new webpack.ProvidePlugin({ 
            process: 'process/browser.js', 
        }), 
    ],
}    
Copy the code

4, Uncaught ReferenceError: Buffer is not defined

The error message

Uncaught ReferenceError: Buffer is not defined
Copy the code

The solution

module.exports = {
    plugins: [ 
        //...
        new webpack.ProvidePlugin({ 
            //...
            Buffer: ['buffer', 'Buffer']
        }), 
    ],
}  
Copy the code