React - Webpack 項目腳手架搭建

把手還是伸向了前端,抽空折騰了幾天,算是理清了起步門檻。

一、首先確保安裝了 npm,如果沒裝…那就想辦法裝上
$ npm
Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
    explore, get, help, help-search, i, init, install,
    install-test, it, link, list, ln, login, logout, ls,
    outdated, owner, pack, ping, prefix, profile, prune,
    publish, rb, rebuild, repo, restart, root, run, run-script,
    s, se, search, set, shrinkwrap, star, stars, start, stop, t,
    team, test, token, tst, un, uninstall, unpublish, unstar,
    up, update, v, version, view, whoami

npm <command> -h     quick help on <command>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    /Users/xiaoyu/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

[email protected] /usr/local/lib/node_modules/npm
二、安裝 create-react-app。如果用 WebStorm,可以跳過這一步。

IDE 可以選擇創建 React App,省去了手動執行,所以創建後的目錄內容是一樣的。

// -g : global
$ npm install create-react-app -g
/usr/local/bin/create-react-app -> /usr/local/lib/node_modules/create-react-app/index.js
+ [email protected]
added 91 packages in 24.685s

$ create-react-app
Please specify the project directory:
  create-react-app <project-directory>

For example:
  create-react-app my-react-app

Run create-react-app --help to see all options.

如介紹所言,創建一個app,名字任意,合法即可

$ create-react-app my-react-app

項目結構如下:

$ ls my-react-app
README.md		    package-lock.json	public
node_modules		package.json		src
  • README.md : 你懂的
  • node_moudles : 依賴都在找個目錄下
  • package.json : npm的配置文件,或者說是項目的配置文件
  • package-lock.json : 鎖定版本號
  • public : 存放靜態資源
  • src : 代碼/資源

三、安裝 webpack 全家桶

npm install 參數說明:package.json 有幾個依賴節點,dependenciesdevDependenciesoptionalDependencies,前者會隨着項目發佈出去;後者顧名思義,只在開發時使用;後後者爲可選階段


-S, --save :依賴添加到 dependencies 節點,
-D,–save-dev :依賴添加到 devDependencies 節點
-O,–save-optional :依賴添加到 optionalDependencies 節點

以下命令,在項目根目錄下執行

// 也可以放在一行執行
$ npm install webpack -D
$ npm install webpack-cli -D
$ npm install webpack-dev-server -D

注意,這裏有個坑:這三個依賴的版本號一定要相互匹配,如果你要指定版本,一定要確認指定的版本號是行不通的,不然就會報錯。都用最新版,目前一切正常。

四、配置 webpack server

鑑於 webpack 可用於本地 server,也可用於打包,各自使用不同的配置文件。在項目根目錄創建個文件夾 wepack,用於存放 webpack 配置文件。

  1. webpack/webpack.config.js,用於開發 server
const path = require('path');
const webpack = require('webpack');
const __repo = path.dirname(__dirname);
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: { // 程序唯一入口
        'index': path.resolve(__repo, 'src/index.jsx'),
    },
    mode: 'development',
    output: { // 打包文件輸出位置
        path: path.resolve(__repo, "build"),
        filename: "bundle.js",
        publicPath: "/"
    },
    devServer: {
        contentBase: [path.join(__repo, 'public'),], // 本地服務器索價在的頁面所在目錄
        compress: false,
        port: 7788, // server 使用端口
        disableHostCheck: true,
        inline: true, // 實時刷新
        historyApiFallback: true, // 不跳轉
        hot: true
    },
    module: {
        rules: [
            {
                test: /(\.jsx|\.js)$/, // 匹配所護理文件的擴展名正則表達式
                exclude: /(node_modules|bower_components)/, // 手動添加/屏蔽的文件
                use: {
                    loader: 'babel-loader', // loader名稱
                }
            },
            {
                test: /\.(css|styl)$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader'
                    }
                 ]
            },
            {
                test: /\.html$/,
                use: [
                    {loader: 'html-loader'}
                ]
            },
            {
                test: /\.(gif|jpg|png|svg|ttf|eot|woff|woff2)$/,
                use : {
                    loader: 'file-loader?name=fonts/[name].[ext]'
                }
            },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'public/index.html'
        })
    ]
};

其中的 module,就是 webpack 的 loader,都是用來打包用的:

  • babel-loader:打包jsx、js文件,轉化成瀏覽器認識的格式,因該loader配置選項較多,一般單抽取出獨立的文件.bebelrc,放在項目根目錄,webpack可以自動識別到
  • css-loaderstyle-loader:打包css、style文件
  • html-loader:打包html文件
  • file-loader:打包其他格式文件,如配置中所寫

.babelrc 內容如下:

{
  "presets": ["@babel/preset-react", "@babel/preset-env"], // 支持的編碼
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

其中,所有的loader、plugin,都需要手動安裝

$ npm install -D babel-core babel-loader css-loader style-loader html-loader file-loader

$ npm install -D @babel/preset-env @babel/preset-react @babel/plugin-transform-runtime html-webpack-plugin
  1. 配置 package.json,使用webpack/webpack.config.js。修改 package.json 中的scripts 節點,如下:
"dev": "webpack-dev-server --config webpack/webpack.config.js"

此時,在項目根目錄下執行該命令,即可。

$ npm run dev

五、配置 webpack 打包配置

和 server 類似,這裏直接貼上配置文件

  1. webpack/webpack.config.build.js
const path = require('path');
const webpack = require('webpack');
const __repo = path.dirname(__dirname);
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    mode: "production",
    entry: path.resolve(__repo, 'src/index.jsx'),
    devtool: "#source-map",
    output: {
        path: path.resolve(__repo, "dist"),
        filename: "app/[name].bundle.js",
        publicPath: "/"
    },
    module: {
        rules: [
            {
                test: /(\.jsx|\.js)$/, // 匹配所護理文件的擴展名正則表達式
                exclude: /(node_modules|bower_components)/, // 手動添加/屏蔽的文件
                use: {
                    loader: 'babel-loader', // loader名稱
                }
            },
            {
                test: /\.(css|styl)$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader'
                    }
                ]
            },
            {
                test: /\.html$/,
                use: [
                    {loader: 'html-loader'}
                ]
            },
            {
                test: /\.(gif|jpg|png|svg|ttf|eot|woff|woff2)$/,
                use : {
                    loader: 'file-loader?name=fonts/[name].[ext]'
                }
            },
        ]
    },

    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'public/index.html'
        })
    ]
};
  1. 修改package.json中的scripts節點,如下
"build": "webpack --config webpack/webpack.config.build.js"

執行打包命令後,所有文件會輸出到項目根目錄下的dist中。

$ npm run build

打包後的文件,配合nginx就可以訪問請求了。

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章