27.用webpack自搭react和vue框架

本身搭建react-app vue-cli

前置條件

cnpm i -D webpack webpack-cli webpack-dev-servercss

cnpm i -D css-loader style-loader url-loader file-loaderhtml

cnpm i -D html-webpack-plugin clean-webpack-plugin前端

webpack.config.jsvue

webpack <==> webpack --config webpack.config.jsnode

webpack --config vue.config.jsreact

組成:
{
    mode  開發、生產模式
    
    loader
    
    plugin
    
    devServer ----> webpack-dev-server
}

react

cnpm i -S react react-domwebpack

cnpm i -D babel-loader babel-core babel-preset-env babel-preset-reactgit

預設:.babelrc { "presets": ["env", "react"] }web

.babelrc:ES6解析的配置vue-cli

實例:

image

+  public:

1[index.html]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>myapp</title>
</head>
<body>
    <div id="app">app</div>
</body>
</html>

+  src:

1[App.js] 
import React,{Component} from "react";
import img from "./asset/logo.png";

const Home = ()=> <div>Home</div>

export default class App extends Component{
    //測試
    constructor(...args){
        super(...args);
        this.state={count:100}
    }
    plus(){
        this.setState({
            count:this.state.count+1
        })
    }
    render(){
        return <div>
           <Home />
           {this.state.count}
           <input onClick={this.plus.bind(this)} type="button" value="按鈕"/>
            <img src={img} />
        </div>
    }
}


2[index.js]

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App/>,document.getElementById("app"));

+  [.babelrc]  ES6解析的配置
{ "presets": ["env", "react"] }

+  webpack.config.js 配置文件
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports ={
    mode:"development",
    entry:"./src/index.js",
    output:{
        path: path.resolve(__dirname, "./dist"),
        filename: "app.bundle.js"
    },
    devServer:{
        port:9000,
        open:true,
    },
    plugins: [
        new CleanWebpackPlugin(['./dist']),
        new HtmlWebpackPlugin({
            template:'./public/index.html',
            filename: 'index.html'
        })
    ],
    module:{
        rules:[
            {test: /\.css$/, use: ['style-loader','css-loader']},
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,//排除
                use: 'babel-loader'
            },
            {
                test: /\.(png|jpg|gif)$/i,
                use: [
                  {
                    loader: 'url-loader',
                    options: {
                      limit: 8192
                    }
                  }
                ]
            },
        ]
    }
}


+  [package.json] 工程文件

{
  "name": "react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "clean-webpack-plugin": "^0.1.19",
    "css-loader": "^1.0.0",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.22.1",
    "url-loader": "^1.1.0",
    "webpack": "^4.16.5",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  },
  "dependencies": {
    "react": "^16.4.2",
    "react-dom": "^16.4.2"
  }
}

vue

cnpm i -S vue

cnpm i -D babel-loader babel-core babel-preset-env
cnpm i -D vue-loader vue-template-compiler

預設:.babelrc { "presets": ["env"] }

實例

image

+  [public]

1[index.html]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>MyApp</title>
</head>
<body>
    <div id="app">app</div>
</body>
</html>

+  [src]

1[main.js]
import Vue from "vue";
import App from "./App.vue";

new Vue({
    render:h=>h(App)
}).$mount("#app")

2[App.vue]
<template>
    <div id="app">
        {{msg}}
    </div>
</template>
<script>
export default{
    name:"App",
    data(){
        return {
            msg:"MyVue App"
        }
    }
} 
    
</script>
<style>
#app{color:red;}
</style>

3[asset]=>logo.png

+  [.babelrc]
{ "presets": ["env"] }

+  [package.json]

{
  "name": "vue",
  "version": "1.0.0",
  "description": "",
  "main": "vue.config.js",
  "scripts": {
    "test": "cross-env NODE_ENV=development   webpack --config test.js",
    "serve": "cross-env NODE_ENV=development  webpack-dev-server  --progress --config vue.config.js",
    "serve2": "webpack-dev-server --config vue.config.js",
    "dev": "webpack --config vue.config.js",
    "build": "set NODE_ENV=development && webpack --config vue.config.js",
    "build2": "set NODE_ENV=production && webpack --config vue.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "clean-webpack-plugin": "^0.1.19",
    "cross-env": "^5.2.0",
    "css-loader": "^1.0.0",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.22.1",
    "uglifyjs-webpack-plugin": "^1.3.0",
    "url-loader": "^1.1.0",
    "vue-loader": "^15.3.0",
    "vue-template-compiler": "^2.5.17",
    "webpack": "^4.16.5",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  },
  "dependencies": {
    "vue": "^2.5.17"
  }
}


+  [vue.config.js]

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
//const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

console.log("====================================");
console.log("process.env:",process.env.NODE_ENV);
console.log("====================================");

process.env.NODE_ENV = process.env.NODE_ENV||"production";
const isDev = process.env.NODE_ENV == "development"?true:false;
const mode = isDev?"development":"production";
function resolve (dir) {
    return path.join(__dirname,dir)
}
module.exports={
    mode,
    //mode:"production",
    entry:"./src/main.js",
    output: {
        path: path.resolve(__dirname, "./dist"),
        filename: "main.bundle.js"
    },
    resolve:{
        extensions: ['.js', '.vue', '.json',".css"],
         alias: {
           'vue$': 'vue/dist/vue.esm.js',
           '@': resolve('src'),
         }
    },
    devServer:{
        port:9000,
        open:true,
    },
    plugins:[
        //new UglifyJsPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
              //NODE_ENV: JSON.stringify(process.env.NODE_ENV)
              NODE_ENV: JSON.stringify(mode)
            }
        }),
        new CleanWebpackPlugin(['./dist']),
        new HtmlWebpackPlugin({
            template:'./public/index.html',
            filename: 'index.html'
        }),
        new VueLoaderPlugin()
    ],
    module:{
        rules:[
            { test: /\.vue$/, loader: 'vue-loader' },
            { test: /\.css$/, use: ['style-loader','css-loader'] },
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,//排除
                use: 'babel-loader'
            },
            {
                test: /\.(png|jpg|gif)$/i,
                use: [
                  {
                    loader: 'url-loader',
                    options: {
                      limit: 8192
                    }
                  }
                ]
            },
        ]
    }

}

cnpm i -D cross-env 兼容環境變量

DefinePlugin mode設置開發者仍是生產版本

mode:production 會自動壓縮代碼

本身手動壓縮代碼:
mode:development
cnpm i -D uglifyjs-webpack-plugin

vue項目目錄做用

1. build文件夾:打包配置的文件夾
  1.1  webpack.base.conf.js :打包的核心配置
  1.2  build.js:構建生產版本,項目開發完成以後,經過build.js打包(加載base與prod,讀取完以後經過webjpack命令對項目進行打包)
  1.3  webpack.prod.conf.js:被build.js調用,webpack生產包的一個配置。基礎代碼都在1.1裏面寫,1.3是對1.1的擴展與補充
  1.4  dev-client.js:熱更新的插件,進行對客戶端進行重載
  1.5  dev-server.js:服務器。(背後的原理是啓動一個express框架,這是一個基於node作的一個後端框架,後端框架能夠在前端起一個服務)
  1.6  vue-loader.conf.js:被base加載,
  1.7  utils.js:工具類,公共的配置
2. config文件夾:打包的配置,webpack對應的配置
  2.1 index.js:可與1.1合併成一個文件,但因爲spa想作一個清晰的架構,所以把它們拆分開了
3. src文件夾:開發項目的源碼
4. App.vue : 入口組件
5. static文件夾:靜態資源,圖片
6. .babelrc:ES6解析的配置
7. .gitignore:忽略某個或一組文件git提交的一個配置
8. index.html:單頁面的入口,經過webpack的打包構建以後,會對src源碼進行編譯,最終把它們插入到html裏面來
9. package.json:基礎配置,告訴咱們項目的信息(版本號、項目姓名、依賴)
10. node_modulues:項目的安裝依賴
相關文章
相關標籤/搜索