webpack4和react 建構多頁面應用的實作方法
這篇文章要跟大家介紹的內容是關於webpack4和react 搭建多頁面應用程式的實作方法,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
webpack 升級到4之後還沒好好的同步一個可實用的webpack架子,接下來用webpack4來搭建一個簡單的react的多界面應用,廢話不說 直接擼碼
建立工程
$ mkdir demo && cd demo $ npm init -y
目錄架構
![工程目录结构][1]
webpack 設定
安装react + babel 依赖 $ npm i -S react@16.3.0 react-dom@16.3.0 $ npm i -D webpack@4.4.1 webpack-cli@2.0.13 webpack-dev-server@3.1.1 webpack-merge@4.1.2 babel-cli@6.26.0 babel-preset-env@1.6.1 babel-preset-react@6.24.1 babel-preset-react-hmre@1.1.1 babel-loader@7.1.4 file-loader@1.1.11 url-loader@1.0.1
webpack.base.conf.js(config -> webpack)
const entry = require("./webpack.entry.conf"); const newEntry = {}; for (let name in entry) { newEntry[name] = entry[name][0] } let config = { entry: newEntry, resolve: { extensions: [".js", ".json", ".jsx", ".css", ".pcss"], } }; module.exports = config;
webpack.dev.conf.js
const webpack = require('webpack');//引入webpack const opn = require('opn');//打开浏览器 const merge = require('webpack-merge');//webpack配置文件合并 const path = require("path"); const baseWebpackConfig = require("./webpack.base.conf");//基础配置 const webpackFile = require("./webpack.file.conf");//一些路径配置 const eslintFormatter = require('react-dev-utils/eslintFormatter'); let config = merge(baseWebpackConfig, { /*设置开发环境*/ mode: 'development', output: { path: path.resolve(webpackFile.devDirectory), filename: 'js/[name].js', chunkFilename: "js/[name].js", publicPath: '' }, optimization: { runtimeChunk: { name: 'manifest' }, // 包拆分 splitChunks: { cacheGroups: { common: { // 项目的公共组件 chunks: "initial", name: "common", minChunks: 2, maxInitialRequests: 5, minSize: 0 }, vendor: { // 第三方组件 test: /node_modules/, chunks: "initial", name: "vendor", priority: 10, enforce: true } } } }, plugins: [ /*设置热更新*/ new webpack.HotModuleReplacementPlugin(), ], module: { rules: [ { test: /\.(js|jsx)$/, use: [ 'babel-loader', 'cache-loader', ], include: [ path.resolve(__dirname, "../../app"), path.resolve(__dirname, "../../entryBuild") ], exclude: [ path.resolve(__dirname, "../../node_modules") ], }, { test: /\.(css|pcss)$/, loader: 'style-loader?sourceMap!css-loader?sourceMap!postcss-loader?sourceMap', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg|swf)$/, loader: 'file-loader?name=[name].[ext]&outputPath=' + webpackFile.resource + '/' }, { test: /\.(js|jsx)$/, enforce: 'pre', use: [ { options: { formatter: eslintFormatter, eslintPath: require.resolve('eslint'), // @remove-on-eject-begin baseConfig: { extends: [require.resolve('eslint-config-react-app')], }, //ignore: false, useEslintrc: false, // @remove-on-eject-end }, loader: require.resolve('eslint-loader'), }, ], include: [ path.resolve(__dirname, "../../app") ], exclude: [ path.resolve(__dirname, "../../node_modules") ], } ] }, /*设置api转发*/ devServer: { host: '0.0.0.0', port: 8080, hot: true, inline: true, contentBase: path.resolve(webpackFile.devDirectory), historyApiFallback: true, disableHostCheck: true, proxy: [ { context: ['/api/**', '/u/**'], target: 'http://10.8.200.69:8080/', secure: false } ], /*打开浏览器 并打开本项目网址*/ after() { opn('http://localhost:' + this.port); } } }); module.exports = config;
webpack.prod.conf.js
const path = require('path'); const merge = require('webpack-merge'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const baseWebpackConfig = require("./webpack.base.conf"); const webpackFile = require('./webpack.file.conf'); const entry = require("./webpack.entry.conf"); const webpackCom = require("./webpack.com.conf"); let config = merge(baseWebpackConfig, { /*设置生产环境*/ mode: 'production', output: { path: path.resolve(webpackFile.proDirectory), filename: 'js/[name].[chunkhash:8].js', chunkFilename: "js/[name]-[id].[chunkhash:8].js", }, optimization: { //包清单 runtimeChunk: { name: "manifest" }, //拆分公共包 splitChunks: { cacheGroups: { common: { //项目公共组件 chunks: "initial", name: "common", minChunks: 2, maxInitialRequests: 5, minSize: 0 }, vendor: { //第三方组件 test: /node_modules/, chunks: "initial", name: "vendor", priority: 10, enforce: true } } } }, plugins: [ // extract css into its own file new ExtractTextPlugin('css/[name].[md5:contenthash:hex:8].css'), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ assetNameRegExp: /\.css$/g, cssProcessor: require('cssnano'), cssProcessorOptions: { discardComments: {removeAll: true}, // 避免 cssnano 重新计算 z-index safe: true }, canPrint: true }), ], module: { rules: [ { test: /\.(js|jsx)$/, use: [ 'babel-loader', ], }, { test: /\.(js|jsx)$/, loader: 'babel-loader', exclude: /node_modules/, }, { test: /\.(css|pcss)$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader!postcss-loader" }) }, { test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg)$/, loader: 'url-loader?limit=8192&name=[name].[hash:8].[ext]&publicPath=' + webpackFile.resourcePrefix + '&outputPath=' + webpackFile.resource + '/' }, { test: /\.swf$/, loader: 'file?name=js/[name].[ext]' } ] } }); let pages = entry; for (let chunkName in pages) { let conf = { filename: chunkName + '.html', template: 'index.html', inject: true, title: webpackCom.titleFun(chunkName,pages[chunkName][1]), minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunks: ['manifest', 'vendor', 'common', chunkName], hash: false, chunksSortMode: 'dependency' }; config.plugins.push(new HtmlWebpackPlugin(conf)); } /* 清除 dist */ config.plugins.push(new CleanWebpackPlugin([webpackFile.proDirectory], {root: path.resolve(__dirname, '../../'), verbose: true, dry: false})); /* 拷贝静态资源 */ copyArr.map(function (data) { return config.plugins.push(data) }); module.exports = config;
建立多重介面
整体架构搭建起来之后 app -> component $ mkdir demo && cd demo $ touch Index.jsx import React from 'react'; class Index extends React.Component { render() { return ( <p className="demo"> 写个demo </p> ); } } export default Index;
在config -> entry
module.exports = [ { name: 'index', path: 'index/Index.jsx', title: '首页', keywords: '首页', description: '首页' }, { name: 'demo', path: 'demo/Index.jsx', title: 'demo', keywords: 'demo', description: 'demo' }, { name: 'demo1', path: 'demo1/Index.jsx', title: 'demo1', keywords: 'demo1', description: 'demo1' } ];
接著直接執行npm run create-dev 就會在devBuild 和entryBuild 中加入一個新的demo.html 和demo.js
package.json
{ "name": "webpack_es6", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack-dev-server --devtool eval --progress --colors --profile --config config/webpack/webpack.dev.conf.js", "entry": "node config/entry/entryBuild.js", "devBuildHtml": "node config/webpack/webpack.devBuildHtml.conf.js", "create-dev": "npm run entry && npm run devBuildHtml", "build": "BABEL_ENV=production && webpack --progress --colors --config config/webpack/webpack.prod.conf.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "react": "^16.3.0", "react-dom": "^16.3.0" }, "devDependencies": { "babel-cli": "^6.26.0", "babel-eslint": "^8.2.2", "babel-loader": "^7.1.4", "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.24.1", "babel-preset-react-hmre": "^1.1.1", "cache-loader": "^1.2.2", "clean-webpack-plugin": "^0.1.19", "copy-webpack-plugin": "^4.5.1", "css-loader": "^0.28.11", "eslint": "^4.19.1", "eslint-config-react-app": "^2.1.0", "eslint-loader": "^2.0.0", "eslint-plugin-flowtype": "^2.46.1", "eslint-plugin-import": "^2.10.0", "eslint-plugin-jsx-a11y": "^5.1.1", "eslint-plugin-react": "^7.7.0", "extract-text-webpack-plugin": "^4.0.0-beta.0", "file": "^0.2.2", "file-loader": "^1.1.11", "html-webpack-plugin": "^3.1.0", "optimize-css-assets-webpack-plugin": "^4.0.0", "postcss-cssnext": "^3.1.0", "postcss-loader": "^2.1.3", "precss": "^3.1.2", "react-dev-utils": "^5.0.0", "style-loader": "^0.20.3", "url-loader": "^1.0.1", "webpack": "^4.4.1", "webpack-cli": "^2.0.13", "webpack-dev-server": "^3.1.1", "webpack-merge": "^4.1.2" }, "eslintConfig": { "extends": "react-app", "rules": { "import/no-webpack-loader-syntax": 0, "no-script-url": 0, "jsx-a11y/href-no-hash": 2 } } }
開發環境小技巧
在開發環境中加入cache-loader 可以提昇在開發環境的編譯速度
相關文章推薦:
react antd-mobile專案中如何實作css 與less 局部作用域化的功能
以上是webpack4和react 建構多頁面應用的實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在 Vue.js 中使用 Bootstrap 分為五個步驟:安裝 Bootstrap。在 main.js 中導入 Bootstrap。直接在模板中使用 Bootstrap 組件。可選:自定義樣式。可選:使用插件。

HTML定義網頁結構,CSS負責樣式和佈局,JavaScript賦予動態交互。三者在網頁開發中各司其職,共同構建豐富多彩的網站。

WebDevelovermentReliesonHtml,CSS和JavaScript:1)HTMLStructuresContent,2)CSSStyleSIT和3)JavaScriptAddSstractivity,形成thebasisofmodernWebemodernWebExexperiences。

要設置 Bootstrap 框架,需要按照以下步驟:1. 通過 CDN 引用 Bootstrap 文件;2. 下載文件並將其託管在自己的服務器上;3. 在 HTML 中包含 Bootstrap 文件;4. 根據需要編譯 Sass/Less;5. 導入定製文件(可選)。設置完成後,即可使用 Bootstrap 的網格系統、組件和样式創建響應式網站和應用程序。

創建 Bootstrap 分割線有兩種方法:使用 標籤,可創建水平分割線。使用 CSS border 屬性,可創建自定義樣式的分割線。

在 Bootstrap 中插入圖片有以下幾種方法:直接插入圖片,使用 HTML 的 img 標籤。使用 Bootstrap 圖像組件,可以提供響應式圖片和更多樣式。設置圖片大小,使用 img-fluid 類可以使圖片自適應。設置邊框,使用 img-bordered 類。設置圓角,使用 img-rounded 類。設置陰影,使用 shadow 類。調整圖片大小和位置,使用 CSS 樣式。使用背景圖片,使用 background-image CSS 屬性。

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

如何使用 Bootstrap 按鈕?引入 Bootstrap CSS創建按鈕元素並添加 Bootstrap 按鈕類添加按鈕文本
