How to use webpack+react+antd scaffolding in actual projects
This time I will show you how to use webpack react antd scaffolding in actual projects, and what are the precautions for using webpack react antd scaffolding in actual projects. The following is a practical case, let's take a look.
Optimization category
Style separation
Separation of third-party resources
Differentiate development environment
Hot update
- ##Extract public code
1. CSS separation
npm install extract-text-webpack-plugin -D
+ let cssExtract = new ExtractTextWebpackPlugin({ + filename: 'css.css', + allChunks: true + }); + let sassExtract = new ExtractTextWebpackPlugin('sass.css') + let lessExtract = new ExtractTextWebpackPlugin('less.css')
- test: regular expression that matches the extension of the processed file
- include /exclude Manually specify folders that must be processed or block folders that do not need to be processed
{ test: /\.css$/, use: cssExtract.extract({ fallback: "style-loader", use: ['css-loader?minimize','postcss-loader'], publicPath: "/dist" }), include:path.join(__dirname,'./src'), exclude:/node_modules/ }, { test: /\.scss$/, use: sassExtract.extract({ fallback: "style-loader", use: ["css-loader?minimize","sass-loader"], publicPath: "/dist" }), include:path.join(__dirname,'./src'), exclude:/node_modules/ }, { test: /\.less$/, loader: lessExtract.extract({ use: ["css-loader?minimize", "less-loader"] }), include:path.join(__dirname,'./src'), exclude:/node_modules/ },
compilation.mainTemplate.applyPluginsWaterfall is not a functionUse Chunks.groupsIterable and filter by instanceof Entrypoint insteadThe research concluded that the reason why webpack was upgraded to v4 but the corresponding plug-in was not upgraded. Solution: Install the specified version of dependencies
"html-webpack-plugin": "^3.0.4" "extract-text-webpack-plugin": "^4.0.0-beta.0"
resolve
After specifying the extension, you don’t need to add the file extension when requiring or importing , will try to add extensions in order to matchresolve: { //引入模块的时候,可以不用扩展名 extensions: [".js", ".less", ".json"], alias: {//别名 "bootstrap": "bootstrap/dist/css/bootstrap.css" } }
Listen to file modification
Used in webpack mode, not used in webpack-dev-server mode, you can change watch to falsewatchOptions: { ignored: /node_modules/, aggregateTimeout: 300, //监听到变化发生后等300ms再去执行动作,防止文件更新太快导致编译频率太高 poll: 1000 //通过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次 }
Extract public code
optimization: { splitChunks: { cacheGroups: { commons: { chunks: "initial", minChunks: 2, maxInitialRequests: 5, // The default limit is too small to showcase the effect minSize: 0 // This is example is too small to create commons chunks }, vendor: { test: /node_modules/, chunks: "initial", name: "vendor", priority: 10, enforce: true } } } }
Separate react react-dom ant public code
Method 1: externalsIntroduce a third-party resource library to the page, and then use externals to prevent certain imported packages from being packaged into the bundle. Instead, obtain these external dependencies at runtime (runtime). .
<script src="https://cdn.bootcss.com/react/16.4.0-alpha.0911da3/cjs/react.production.min.js"></script> <script src="https://cdn.bootcss.com/react-dom/16.4.0-alpha.0911da3/cjs/react-dom-server.browser.production.min.js"></script> externals: { 'react': 'React', 'react-dom': 'ReactDOM', // 提出ant design的公共资源, }
<script src="./vendor/react.dll.js"></script>
var path = require('path'); var webpack = require('webpack'); var ExtractTextWebpackPlugin = require("extract-text-webpack-plugin"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const CleanWebpackPlugin = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin') let cssExtract = new ExtractTextWebpackPlugin({ filename: 'css.css', allChunks: true }); let sassExtract = new ExtractTextWebpackPlugin('sass.css') let lessExtract = new ExtractTextWebpackPlugin('less.css') module.exports = { entry:'./src/index.js', output: { path: path.resolve(__dirname, './dist'), filename: 'bundle.[hash:8].js', publicPath: '' }, resolve: { //引入模块的时候,可以不用扩展名 extensions: [".js", ".less", ".json"], alias: {//别名 "bootstrap": "bootstrap/dist/css/bootstrap.css" }, modules: [path.resolve(__dirname, 'node_modules')] }, /* externals: { 'react': 'React', 'react-dom': 'ReactDOM', // 提出ant design的公共资源 //'antd': 'antd', },*/ devtool: 'source-map', devServer: { contentBase:path.resolve(__dirname,'dist'), publicPath: '/', port: 8080, hot:true, compress:true, historyApiFallback: true, inline: true }, watch: false, //只有在开启监听模式时,watchOptions才有意义 watchOptions: { ignored: /node_modules/, aggregateTimeout: 300, //监听到变化发生后等300ms再去执行动作,防止文件更新太快导致编译频率太高 poll: 1000 //通过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次 }, optimization: { splitChunks: { cacheGroups: { commons: { chunks: "initial", minChunks: 2, maxInitialRequests: 5, // The default limit is too small to showcase the effect minSize: 0 // This is example is too small to create commons chunks }, vendor: { test: /node_modules/, chunks: "initial", name: "vendor", priority: 10, enforce: true } } } }, module: { rules:[ { test: /\.js$/, use: { loader:'babel-loader', options: { presets: ['env','es2015', 'react'], } }, include:path.join(__dirname,'./src'), exclude:/node_modules/ }, { test: /\.css$/, use: cssExtract.extract({ fallback: "style-loader", use: ['css-loader?minimize','postcss-loader'], publicPath: "/dist" }), include:path.join(__dirname,'./src'), exclude:/node_modules/ }, { test: /\.scss$/, use: sassExtract.extract({ fallback: "style-loader", use: ["css-loader?minimize","sass-loader"], publicPath: "/dist" }), include:path.join(__dirname,'./src'), exclude:/node_modules/ }, { test: /\.less$/, loader: lessExtract.extract({ use: ["css-loader?minimize", "less-loader"] }), include:path.join(__dirname,'./src'), exclude:/node_modules/ }, { test: /\.(html|htm)/, use: 'html-withimg-loader' }, { test: /\.(png|jpg|gif|svg|bmp|eot|woff|woff2|ttf)/, use: { loader:'url-loader', options:{ limit: 5 * 1024, //指定拷贝文件的输出目录 outputPath: 'images/' } } } ] }, plugins: [ //定义环境变量 new webpack.DefinePlugin({ __development__: JSON.stringify(process.env.NODE_ENV) }), new CleanWebpackPlugin(['dist']), cssExtract, lessExtract, sassExtract, new HtmlWebpackPlugin({ title: 'React Biolerplate by YuanYuan', template: './src/index.html', filename: `index.html`, hash: true }), new webpack.DllReferencePlugin({ manifest: path.join(__dirname, 'vendor', 'react.manifest.json') }), new CopyWebpackPlugin([{ from: path.join(__dirname,'vendor'),//静态资源目录源地址 to:'./vendor' //目标地址,相对于output的path目录 }]), /* new webpack.optimize.CommonsChunkPlugin({ name: 'common' // 指定公共 bundle 的名称。 + })*/ new webpack.HotModuleReplacementPlugin(), // 热替换插件 new webpack.NamedModulesPlugin() // 执行热替换时打印模块名字 ] };
const path = require('path'); const webpack = require('webpack'); const merge = require('webpack-merge');//用来合并配置文件 const base = require('./webpack.base'); let other = ''; //console.log(process.env.NODE_ENV ) if (process.env.NODE_ENV == 'development') { other = require('./webpack.dev.config'); } else { other = require('./webpack.prod.config'); } //console.log(merge(base, other)); module.exports = merge(base, other); webpack.prod.config.js const path = require('path'); const webpack = require('webpack'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin') module.exports = { output: { filename: 'bundle.min.js', }, plugins: [ new UglifyJSPlugin({sourceMap: true}) ] }
How to use vue slot socket in the project
What are the precautions for using Dom with Angular2
The above is the detailed content of How to use webpack+react+antd scaffolding in actual projects. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.
