摘要:第一步,新建一個文件夾,然后初始化,會生成一個記錄整個項目的依賴包信息安裝新建以下目錄文件,安裝包文件內(nèi)容文件內(nèi)容,作為整個項目的主入口接下來開始配置四大組成部分入口打包后的文件存放地方,會自動新建打包后輸出
第一步,新建一個文件夾,然后npm init -yes初始化,會生成一個package.json記錄整個項目的依賴包信息
安裝webpack cnpm i webpack webpack-dev-server --save-dev
新建以下目錄文件,
安裝react包 cnpm i react react-dom redux react-redux redux-thunk react-router --save-dev
index.html文件內(nèi)容:
react-weChat
index.jsx文件內(nèi)容,作為整個項目的主入口
import ReactDOM from "react-dom"; import React, {Component} from "react"; class App extends Component { render() { returnHello React !!!} } ReactDOM.render(, document.getElementById("root") )
接下來開始配置webpack.config.js:
webpack四大組成部分:entry,output,module,plugins
const srcDir = __dirname + "/src"; const distDir = __dirname + "/dist"; module.exports = { entry: [ srcDir + "/index.jsx" //入口 ], output: { path: distDir,//打包后的文件存放地方,會自動新建 filename: "index.[hash:7].js"http://打包后輸出的文件名,后面跟7位隨機hash值 }, devtool: "source-map", devServer: { contentBase: "./public",//本地服務(wù)器所加載的頁面的目錄 historyApiFallback: true,//不跳轉(zhuǎn) inline: true,//實時刷新 port: 8090, //端口號 hot: true }, module:{}, plugins:[]
再安裝解析jsx的loader及插件去解析jsx和es6語法:cnpm i babel-cli babel-loader babel-preset-env babel-preset-react babel-plugin-react-transform react-transform-hmr --save-dev
module: { rules: [ { test: /(.jsx|.js)$/, use: { loader: "babel-loader", options: { presets: [ "env", "react" ] } }, exclude: /node_modules/ }, //.babelrc { "presets": [ "react", "env" ], "env": { "development": { "plugins": [ [ "react-transform", { "transforms": [ { "transform": "react-transform-hmr", "imports": [ "react" ], "locals": [ "module" ] } ] } ] ] } } }
cnpm i html-webpack-plugin --save-dev
const HtmlWebpackPlugin = require("html-webpack-plugin");//生成新的html文件
plugins: [ new HtmlWebpackPlugin({//根據(jù)模板引入css,js最終生成的html文件 filename: "index.html",//生成文件存放路徑 template: "./public/index.html",//html模板路徑 }),
cnpm i extract-text-webpack-plugin clean-webpack-plugin --save-dev
const ExtractTextPlugin = require("extract-text-webpack-plugin");//分離css和js const CleanWebpackPlugin = require("clean-webpack-plugin");//清緩存 new ExtractTextPlugin("style.css"),//獨立導(dǎo)出css new CleanWebpackPlugin("dist/*.*", { root: __dirname, verbose: true, dry: false })
cnpm i style-loader css-loader postcss-loader autoprefixer --save-dev
{ test: /.css$/, use: [ { loader: "style-loader" //在html中插入