热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

webpack4+react搭建多页面应用

webpack升级到4之后还没好好的同步一个可实用的webpack架子,接下来用webpack4来搭建一个简单的react的多界面应用,废话不说直接撸码创建工程$mkdirdemo
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 (


写个demo

);
}
} 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 可以提升在开发环境的编译速度

推荐阅读
  • Webpack5内置处理图片资源的配置方法
    本文介绍了在Webpack5中处理图片资源的配置方法。在Webpack4中,我们需要使用file-loader和url-loader来处理图片资源,但是在Webpack5中,这两个Loader的功能已经被内置到Webpack中,我们只需要简单配置即可实现图片资源的处理。本文还介绍了一些常用的配置方法,如匹配不同类型的图片文件、设置输出路径等。通过本文的学习,读者可以快速掌握Webpack5处理图片资源的方法。 ... [详细]
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • Html5-Canvas实现简易的抽奖转盘效果
    本文介绍了如何使用Html5和Canvas标签来实现简易的抽奖转盘效果,同时使用了jQueryRotate.js旋转插件。文章中给出了主要的html和css代码,并展示了实现的基本效果。 ... [详细]
  • 本文介绍了前端人员必须知道的三个问题,即前端都做哪些事、前端都需要哪些技术,以及前端的发展阶段。初级阶段包括HTML、CSS、JavaScript和jQuery的基础知识。进阶阶段涵盖了面向对象编程、响应式设计、Ajax、HTML5等新兴技术。高级阶段包括架构基础、模块化开发、预编译和前沿规范等内容。此外,还介绍了一些后端服务,如Node.js。 ... [详细]
  • VueCLI多页分目录打包的步骤记录
    本文介绍了使用VueCLI进行多页分目录打包的步骤,包括页面目录结构、安装依赖、获取Vue CLI需要的多页对象等内容。同时还提供了自定义不同模块页面标题的方法。 ... [详细]
  • 事变是如许的,我写了一个基于jQuery的插件,在传统的开辟形式中,我们须要如今页面引入jQuery.js,然后在引入我们的插件,我们的插件才运用。然则跟着webpack的鼓起,我 ... [详细]
  • OrbitDBPeer 2 Peer Database using CRDTs
    2019独角兽企业重金招聘Python工程师标准Apeer-to-peerdatabaseforthedecentralizedwebOrbitDBisaserverless ... [详细]
  • 本文介绍了如何使用Express App提供静态文件,同时提到了一些不需要使用的文件,如package.json和/.ssh/known_hosts,并解释了为什么app.get('*')无法捕获所有请求以及为什么app.use(express.static(__dirname))可能会提供不需要的文件。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • 本文记录了在vue cli 3.x中移除console的一些采坑经验,通过使用uglifyjs-webpack-plugin插件,在vue.config.js中进行相关配置,包括设置minimizer、UglifyJsPlugin和compress等参数,最终成功移除了console。同时,还包括了一些可能出现的报错情况和解决方法。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • uniapp开发H5解决跨域问题的两种代理方法
    本文介绍了uniapp开发H5解决跨域问题的两种代理方法,分别是在manifest.json文件和vue.config.js文件中设置代理。通过设置代理根域名和配置路径别名,可以实现H5页面的跨域访问。同时还介绍了如何开启内网穿透,让外网的人可以访问到本地调试的H5页面。 ... [详细]
  • NotSupportedException无法将类型“System.DateTime”强制转换为类型“System.Object”
    本文介绍了在使用LINQ to Entities时出现的NotSupportedException异常,该异常是由于无法将类型“System.DateTime”强制转换为类型“System.Object”所导致的。同时还介绍了相关的错误信息和解决方法。 ... [详细]
  • 在加载一个第三方厂商的dll文件时,提示“找不到指定模块,加载失败”。由于缺乏必要的技术支持,百思不得期间。后来发现一个有用的工具 ... [详细]
  • 点击上方“新机器视觉”,选择加”星标”或“置顶”重磅干货,第一时间送达很早就想总结一下前段时间学习HALCON的心得,但由于其他的事情总是抽不出时间。去年有过一段时间的集中学习,做 ... [详细]
author-avatar
手机用户2602926907
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有