이번에는 webpack으로 React 개발 환경을 구축하는 단계에 대해 자세히 설명하겠습니다. webpack으로 React 개발 환경을 구축할 때 주의 사항은 무엇인가요?
1.프로젝트 초기화
mkdir react-redux && cd react-redux npm init -y
2. Install webpack
npm i webpack -D
npm i -D는 npm install --save-dev의 약어로, 모듈을 설치하고 package.json의 devDependency는 주로 개발 환경의 종속성 패키지입니다. webpack 4+ 버전을 사용하는 경우 CLI도 설치해야 합니다.
npm install -D webpack webpack-cli
3. 새 프로젝트 구조 만들기
react-redux |- package.json + |- /dist + |- index.html |- /src |- index.js
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p id="root"></p> <script src="bundle.js"></script> </body> </html>
index.js
document.querySelector('#root').innerHTML = 'webpack使用';
비 전역 설치 시 패키징.
node_modules\.bin\webpack src\index.js --output dist\bundle.js --mode development
dist 디렉토리에서 html을 열어 webpack을 표시합니다.
을 사용하여 webpack
1을 사용하여 구성 파일
const path=require('path'); module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:path.resolve(dirname,'dist') } };
을 사용하여 node_modules.binwebpack -- 모드 프로덕션
확인 2.NPM 스크립트(NPM 스크립트)를 패키지하려면 package.json에 npm 스크립트(npm 스크립트)를 추가합니다. "build": "webpack --mode Production"
실행 npm run build 패키지 준비node_modules.binwebpack --mode production
可以以进行打包 2.NPM 脚本(NPM Scripts) 在在 package.json 添加一个 npm 脚本(npm script): "build": "webpack --mode production"
运行 npm run build
即可打包
使用webpack构建本地服务器
webpack-dev-server 提供了一个简单的 web 服务器,并且能够实时重新加载。
1.安装 npm i -D webpack-dev-server
修改配置文件webpack.config.js
const path=require('path'); module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:path.resolve(dirname,'dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 } };
运行 webpack-dev-server --progress ,浏览器打开localhost:3000,修改代码会实时显示修改的结果. 添加scripts脚本,运行 npm start 自动打开 http://localhost:8080/
"start": "webpack-dev-server --open --mode development"
启动webpack-dev-server后,在目标文件夹中是看不到编译后的文件的,实时编译后的文件都保存到了内存当中。因此使用webpack-dev-server进行开发的时候都看不到编译后的文件
2.热更新
配置一个webpack自带的插件并且还要在主要js文件里检查是否有module.hot
plugins:[ //热更新,不是刷新 new webpack.HotModuleReplacementPlugin() ],
在主要js文件里添加以下代码
if (module.hot){ //实现热更新 module.hot.accept(); }
在webpack.config.js中开启热更新
devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 hot:true //开启热更新 },
热更新允许在运行时更新各种模块,而无需进行完全刷新.
配置Html模板
1.安装html-webpack-plugin插件
npm i html-webpack-plugin -D
2.在webpack.config.js里引用插件
const path=require('path'); let webpack=require('webpack'); let HtmlWebpackPlugin=require('html-webpack-plugin'); module.exports={ entry:'./src/index.js', output:{ //添加hash可以防止文件缓存,每次都会生成4位hash串 filename:'bundle.[hash:4].js', path:path.resolve('dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 hot:true //开启热更新 }, plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', hash:true, //会在打包好的bundle.js后面加上hash串 }) ] };
运行 npm run build
进行打包,这时候每次npm run build的时候都会在dist目录下创建很多打好的包.应该每次打包之前都将dist目录下的文件清空,再把打包好的文件放进去,这里使用clean-webpack-plugin插件.通过 npm i clean-webpack-plugin -D
命令安装.然后在webpack.config.js中引用插件.
const path=require('path'); let webpack=require('webpack'); let HtmlWebpackPlugin=require('html-webpack-plugin'); let CleanWebpackPlugin=require('clean-webpack-plugin'); module.exports={ entry:'./src/index.js', output:{ //添加hash可以防止文件缓存,每次都会生成4位hash串 filename:'bundle.[hash:4].js', path:path.resolve('dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 hot:true //开启热更新 }, plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', hash:true, //会在打包好的bundle.js后面加上hash串 }), //打包前先清空 new CleanWebpackPlugin('dist') ] };
之后打包便不会产生多余的文件.
编译es6和jsx
1.安装babel npm i babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 -D babel-loader: babel
webpack-dev-server는 간단한 웹 서버를 제공하며 실시간으로 다시 로드할 수 있습니다. 1. npm i -D webpack-dev-server
설치 webpack.config.js
{ "presets": ["env", "stage-0","react"] //从左向右解析 }
const path=require('path'); module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:path.resolve(dirname,'dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true//实时刷新 }, module:{ rules:[ { test:/\.js$/, exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度 use:{ loader:'babel-loader' } } ] } };
npm install --save-dev webpack-merge
const path=require('path'); let webpack=require('webpack'); let HtmlWebpackPlugin=require('html-webpack-plugin'); let CleanWebpackPlugin=require('clean-webpack-plugin'); module.exports={ entry:['babel-polyfill','./src/index.js'], output:{ //添加hash可以防止文件缓存,每次都会生成4位hash串 filename:'bundle.[hash:4].js', path:path.resolve(dirname,'dist') }, plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', hash:true, //会在打包好的bundle.js后面加上hash串 }), //打包前先清空 new CleanWebpackPlugin('dist'), new webpack.HotModuleReplacementPlugin() //查看要修补(patch)的依赖 ], module:{ rules:[ { test:/\.js$/, exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度 use:{ loader:'babel-loader' } } ] } };
const merge=require('webpack-merge'); const path=require('path'); let webpack=require('webpack'); const common=require('./webpack.common.js'); module.exports=merge(common,{ devtool:'inline-soure-map', mode:'development', devServer:{ historyApiFallback: true, //在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html contentBase:path.resolve(dirname, '../dist'),//本地服务器所加载的页面所在的目录 inline: true,//实时刷新 open:true, compress: true, port:3000, hot:true //开启热更新 }, plugins:[ //热更新,不是刷新 new webpack.HotModuleReplacementPlugin(), ], });
1. html-webpack-plugin 플러그인🎜
const merge = require('webpack-merge'); const path=require('path'); let webpack=require('webpack'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode:'production', plugins: [ new UglifyJSPlugin() ] });
react-dom npm i react react-dom -S
npm i clean-webpack-plugin -D
명령을 전달하여 설치하세요. 그런 다음 webpack.config.js에서 플러그인을 참조하세요.🎜import React from 'react'; class App extends React.Component{ render(){ return (<p>佳佳加油</p>); } } export default App;
npm 및 babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 -D babel-loader를 설치합니다. babel
loader babel-preset -env: 구성된 env에 따라 아직 지원되지 않는 기능만 컴파일합니다. babel-preset-react: jsx를 js로 변환🎜🎜2. .babelrc 구성 파일을 추가합니다🎜import React from 'react'; import ReactDOM from 'react-dom'; import {AppContainer} from 'react-hot-loader'; import App from './App'; ReactDOM.render( <AppContainer> <App/> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
npm i -D react-hot-loader
npm install style-loader css-loader url-loader --save-dev
npm install sass-loader node-sass --save-dev
npm install --save-dev mini-css-extract-plugin
{ test:/\.(png|jpg|gif)$/, use:[ "url-loader" ] },
{ test:/\.scss$/, use:[ "style-loader", "css-loader", "sass-loader" ] }
import React from 'react'; import ReactDOM from 'react-dom'; import {AppContainer} from 'react-hot-loader'; import App from './App'; ReactDOM.render( <AppContainer> <App/> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
4.安装 react-hot-loader
npm i -D react-hot-loader
5.修改配置文件 在 webpack.config.js 的 entry 值里加上 react-hot-loader/patch,一定要写在entry 的最前面,如果有 babel-polyfill 就写在babel-polyfill 的后面
6.在 .babelrc 里添加 plugin, "plugins": ["react-hot-loader/babel"]
处理SASS
1.安装 style-loader css-loader url-loader
npm install style-loader css-loader url-loader --save-dev
2.安装 sass-loader node-sass
npm install sass-loader node-sass --save-dev
3.安装 mini-css-extract-plugin ,提取单独打包css文件
npm install --save-dev mini-css-extract-plugin
4.配置webpack配置文件
webpack.common.js
{ test:/\.(png|jpg|gif)$/, use:[ "url-loader" ] },
webpack.dev.js
{ test:/\.scss$/, use:[ "style-loader", "css-loader", "sass-loader" ] }
webpack.prod.js
const merge = require('webpack-merge'); const path=require('path'); let webpack=require('webpack'); const MiniCssExtractPlugin=require("mini-css-extract-plugin"); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode:'production', module:{ rules:[ { test:/\.scss$/, use:[ // fallback to style-loader in development process.env.NODE_ENV !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader, "css-loader", "sass-loader" ] } ] }, plugins: [ new UglifyJSPlugin(), new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css" }) ] });
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
Vue项目webpack打包部署时Tomcat刷新报404错误问题如何处理
위 내용은 Webpack을 사용하여 React 개발 환경을 구축하는 단계에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!