Webpack掉坑之路(1)——HelloWorld(基于npm,react)

前言:

基于ES6風(fēng)格的React以及較新版本的webpack(4.x)和babel等,旨在搬磚和整理,為初學(xué)者和自己提供參考,可能存在許多不足之處,請(qǐng)多指教。

1. 初始化:

首先創(chuàng)建文件夾webpack_demo,然后執(zhí)行命令npm init,進(jìn)行初始化:

> npm init

2. 創(chuàng)建工程目錄:

目錄內(nèi)包括app,config以及public,分別用于存放源代碼文件、配置文件以及輸出文件。創(chuàng)建目錄結(jié)構(gòu)如下:(在cmd控制臺(tái)下,執(zhí)行tree命令)

D:\webpack_demo> tree .
卷 software 的文件夾 PATH 列表
卷序列號(hào)為 8CFF-7734
D:\WEBPACK_DEMO
├─app
├─config
└─public

3. 創(chuàng)建HTML首頁(yè)

在public目錄下,創(chuàng)建一個(gè)index.html,作為主頁(yè),將存放app目錄下的打包輸出文件bundle.js,代碼如下:

<!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>Document</title>
</head>
<body>
    <div id="root"></div>
    <script src="bundle.js"></script>
</body>
</html>

4. 編寫入口文件main.js

在app目錄下,創(chuàng)建一個(gè)main.js,暫時(shí)作為主要入口(entry),該文件將被打包為bundle.js,輸出到public目錄下,代碼如下:

import React,{Component} from 'react';
import ReactDOM from 'react-dom';

class App extends Component{
    render(){
        return (
            <div>Hello, world!</div>
        );
    }
}

ReactDOM.render(
    <App/>,
    document.getElementById('root')
)

此時(shí),需要安裝一下react和react-dom包,命令如下:

> npm install --save react react-dom

5. webpack配置(config/webpack.config.js)

webpack配置好后,即可用webpack命令打包app中的源碼,首先需要安裝webpack相關(guān)依賴包,命令如下:

> npm install --save-dev webpack webpack-cli

然后在config目錄下創(chuàng)建一個(gè)配置文件webpack.config.js,內(nèi)容如下:

const path = require('path');               
const base = path.join(__dirname, '..');    

module.exports={
    devtool: 'eval-source-map',
    entry: path.resolve(base,'app/main.js'),
    output:{
        path: path.resolve(base, 'public'),
        filename: 'bundle.js'
    },
    devServer:{
        contentBase: path.resolve(base, 'public'),
        historyApiFallback: true,                   
        inline: true,                               //實(shí)時(shí)更新
    },
    module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ["@babel/preset-env","@babel/preset-react"],
                plugins: [require('@babel/plugin-proposal-object-rest-spread')]
              }
            }
          }
        ]
    }
};

由于此處用到了babel,而且main.js以es2016的編碼方式,需要用babel來進(jìn)行轉(zhuǎn)換,以兼容之前版本的es,依賴包安裝命令如下:(https://www.npmjs.com/package/babel-loader)

> npm install -D babel-loader @babel/core @babel/preset-env @babel/preset-react

6. 添加啟動(dòng)腳本命令行

在package.json中,向"scripts"項(xiàng)添加執(zhí)行webpack打包命令:

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack --config config/webpack.config.js"
  },

配置完畢后,執(zhí)行命令npm start,可以進(jìn)行打包,打包后我們能夠看到public目錄下多出了一個(gè)bundle.js的文件,說明打包成功。內(nèi)容大概如下所示:

>npm start

> webpack_demo@1.0.0 start D:\webpack_demo
> webpack --config config/webpack.config.js

Hash: e5644b2f4476f963bdc1
Version: webpack 4.20.2
Time: 934ms
Built at: 2018-09-26 23:19:52
    Asset      Size  Chunks             Chunk Names
bundle.js  1.87 MiB    main  [emitted]  main
Entrypoint main = bundle.js
[./app/main.js] 2.66 KiB {main} [built]
    + 11 hidden modules

7. 實(shí)現(xiàn)頁(yè)面實(shí)時(shí)更新

為了能夠在編碼的同時(shí)實(shí)時(shí)更新前端頁(yè)面,我們需要安裝webpack-dev-server
webpack-dev-server的依賴包安裝命令如下:

> npm install --save-dev webpack-dev-server

然后在package.json文件對(duì)應(yīng)的"scripts"中,添加一行執(zhí)行腳本命令:

...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack --config config/webpack.config.js",
    "server": "webpack-dev-server --open --config config/webpack.config.js"
  },
...

8. 啟動(dòng)服務(wù)器

執(zhí)行命令npm run server,具體的服務(wù)器配置信息如上面的webpack.config.js中的"devServer"。 執(zhí)行結(jié)果如下:

D:\webpack_demo>npm run server

> webpack_demo@1.0.0 server D:\VictorLin\workspace\webpack_demo
> webpack-dev-server --open --config config/webpack.config.js

i ?wds?: Project is running at http://localhost:8080/
i ?wds?: webpack output is served from /
i ?wds?: Content not from webpack is served from D:\webpack_demo\public
i ?wds?: 404s will fallback to /index.html
i ?wdm?: wait until bundle finished: /
i ?wdm?: Hash: e734530a0f196c5a077c
Version: webpack 4.20.2
Time: 1218ms
Built at: 2018-09-26 23:31:14
    Asset      Size  Chunks             Chunk Names
bundle.js  2.69 MiB    main  [emitted]  main
Entrypoint main = bundle.js
[./app/main.js] 2.66 KiB {main} [built]
[./node_modules/html-entities/index.js] 231 bytes {main} [built]
[./node_modules/loglevel/lib/loglevel.js] 7.68 KiB {main} [built]
[./node_modules/node-libs-browser/node_modules/punycode/punycode.js] 14.3 KiB {main} [built]
[./node_modules/querystring-es3/index.js] 127 bytes {main} [built]
[./node_modules/react-dom/index.js] 1.33 KiB {main} [built]
[./node_modules/react/index.js] 190 bytes {main} [built]
[./node_modules/url/url.js] 22.8 KiB {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 7.78 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.58 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.05 KiB {main} [built]
[./node_modules/webpack-dev-server/node_modules/strip-ansi/index.js] (webpack)-dev-server/node_modules/strip-ansi/index.js 161 bytes {main} [built]
[0] multi (webpack)-dev-server/client?http://localhost:8080 ./app/main.js 40 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./node_modules/webpack/hot/emitter.js] (webpack)/hot/emitter.js 77 bytes {main} [built]
    + 22 hidden modules
i ?wdm?: Compiled successfully.

如果執(zhí)行成功的話,會(huì)自動(dòng)彈出已經(jīng)將打包好的public/bundle.js的public/index.html頁(yè)面,并顯示"Hello, world!"字眼,結(jié)果如圖:


helloworld!.jpg

我們可以對(duì)app/main.js進(jìn)行修改,比如添加幾個(gè)感嘆號(hào):

//app/main.js
...
class App extends Component{
    render(){
        return (
            <div>Hello, world!!!!!!!</div>
        );
    }
}
...

然后保存,會(huì)看到控制臺(tái)會(huì)繼續(xù)執(zhí)行編譯:

i ?wdm?: Compiling...
i ?wdm?: Hash: c771406eb303106ec693
Version: webpack 4.20.2
Time: 103ms
Built at: 2018-09-26 23:33:50
    Asset      Size  Chunks             Chunk Names
bundle.js  2.69 MiB    main  [emitted]  main
Entrypoint main = bundle.js
[./app/main.js] 2.66 KiB {main} [built]
    + 36 hidden modules
i ?wdm?: Compiled successfully.

過程中包含了執(zhí)行打包、index.html引用bundle.js,結(jié)果如圖,確實(shí)是多了幾個(gè)感嘆號(hào):


helloworld!!!!!!!.jpg

添加style/css loader支持

命令如下:

> npm install --save-dev style-loader css-loader 

webpack.config.js配置如下

//其他配置...
module:{
  rules:[  
        //其他配置... ,
        {   
               test: /\.css$/,
               use: [
                   {
                       loader: "style-loader",
                   },
                   {
                       loader: "css-loader",
                   }
               ]
           }
      ]
}

如此便可以在app目錄下創(chuàng)建一個(gè)css文件,然后讓main.js中的組件引用,結(jié)果如圖:


helloworld!!!!!!!_with_css.jpg

綁定本地IP

在devServer中添加一行host即可綁定本地IP,否則默認(rèn)啟動(dòng)的服務(wù)器只綁定本地的localhost(127.0.0.1),示例如下:

//其他配置項(xiàng)...
    devServer: {
        host: "192.168.4.24",
        port: 3001,
        //其他配置項(xiàng)...
    },

結(jié)束語:

都是照搬大佬們的東西,并沒有什么原創(chuàng)的,但也不至于抄襲文字,僅供自己和其他初學(xué)者學(xué)習(xí),有不足之處,請(qǐng)多多指教。更詳細(xì)教程請(qǐng)參考:
https://segmentfault.com/a/1190000006178770

附錄:

1. package.json

package.json中的內(nèi)容,包括本文中所使用到的各個(gè)依賴包及其版本:

//package.json
{
  "name": "webpack_demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack --config config/webpack.config.js",
    "server": "webpack-dev-server --open --config config/webpack.config.js"
  },
  "author": "Victor",
  "license": "ISC",
  "dependencies": {
    "react": "^16.5.2",
    "react-dom": "^16.5.2"
  },
  "devDependencies": {
    "@babel/core": "^7.1.0",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.2",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.1.9",
    "css-loader": "^1.0.0",
    "style-loader": "^0.23.0"
  }
}

2. webpack.config.js

//config/webpack.config.js
const path = require('path');
const base = path.join(__dirname, '..');

module.exports={
    devtool: 'eval-source-map',
    entry: path.resolve(base,'app/main.js'),
    output:{
        path: path.resolve(base, 'public'),
        filename: 'bundle.js'
    },
    devServer:{
        contentBase: path.resolve(base, 'public'),
        historyApiFallback: true,
        //host: "192.168.4.24",              //配置ip
        //port: 3000,                              //配置端口
        inline: true,                               //實(shí)時(shí)更新
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ["@babel/preset-env","@babel/preset-react"],
                        plugins: [require('@babel/plugin-proposal-object-rest-spread')]
                    }
                }
            },
            {
                test: /\.css$/,
                use: [
                    {
                        loader: "style-loader",
                    },
                    {
                        loader: "css-loader",
                    }
                ]
            }

        ]
    }
};

初始項(xiàng)目的github如下地址,基于React和Antd,只需執(zhí)行初始化命令(npm/yarn install)即可使用:
https://github.com/DeepbigSheng/ReactDemoBasedOnAntd

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容