Setup ReactJS with Webpack

webpack綁定react的工具,將您的所有react編成一個小包,官方網站了解更多關於webpack信息。

接著使用create-react-app來協助生成所有react的項目樣版,不用直接編寫webpack的配置文件。可以將其視為django-admin的命令,但它的功能更強大。

以超級用戶權限來安裝create-react-app,並指定-g參數來進行全域性安裝

npm install -g create-react-app

安裝後,使用create-react-app創建一個react程序,之後彈出配置文件,以利後續的編輯。

create-react-app rcharts
cd rcharts
npm run eject
> rcharts@0.1.0 eject
> react-scripts eject

NOTE: Create React App 2+ supports TypeScript, Sass, CSS Modules and more without ejecting: https://reactjs.org/blog/2018/10/01/create-react-app-v2.html

√ Are you sure you want to eject? This action is permanent. ... yes
Ejecting...

Copying files into D:\apischip.com\rcharts
  Adding \config\env.js to the project
  Adding \config\getHttpsConfig.js to the project
  Adding \config\modules.js to the project
  Adding \config\paths.js to the project
  Adding \config\webpack.config.js to the project
  Adding \config\webpackDevServer.config.js to the project
  Adding \config\jest\babelTransform.js to the project
  Adding \config\jest\cssTransform.js to the project
  Adding \config\jest\fileTransform.js to the project
  Adding \scripts\build.js to the project
  Adding \scripts\start.js to the project
  Adding \scripts\test.js to the project
  Adding \config\webpack\persistentCache\createEnvironmentHash.js to the project

Updating the dependencies
  Removing react-scripts from dependencies
  Adding @babel/core to dependencies
  Adding @pmmmwh/react-refresh-webpack-plugin to dependencies
  Adding @svgr/webpack to dependencies
  Adding babel-jest to dependencies
  Adding babel-loader to dependencies
  Adding babel-plugin-named-asset-import to dependencies
  Adding babel-preset-react-app to dependencies
  Adding bfj to dependencies
  Adding browserslist to dependencies
  Adding camelcase to dependencies
  Adding case-sensitive-paths-webpack-plugin to dependencies
  Adding css-loader to dependencies
  Adding css-minimizer-webpack-plugin to dependencies
  Adding dotenv to dependencies
  Adding dotenv-expand to dependencies
  Adding eslint to dependencies
  Adding eslint-config-react-app to dependencies
  Adding eslint-webpack-plugin to dependencies
  Adding file-loader to dependencies
  Adding fs-extra to dependencies
  Adding html-webpack-plugin to dependencies
  Adding identity-obj-proxy to dependencies
  Adding jest to dependencies
  Adding jest-resolve to dependencies
  Adding jest-watch-typeahead to dependencies
  Adding mini-css-extract-plugin to dependencies
  Adding postcss to dependencies
  Adding postcss-flexbugs-fixes to dependencies
  Adding postcss-loader to dependencies
  Adding postcss-normalize to dependencies
  Adding postcss-preset-env to dependencies
  Adding prompts to dependencies
  Adding react-app-polyfill to dependencies
  Adding react-dev-utils to dependencies
  Adding react-refresh to dependencies
  Adding resolve to dependencies
  Adding resolve-url-loader to dependencies
  Adding sass-loader to dependencies
  Adding semver to dependencies
  Adding source-map-loader to dependencies
  Adding style-loader to dependencies
  Adding tailwindcss to dependencies
  Adding terser-webpack-plugin to dependencies
  Adding webpack to dependencies
  Adding webpack-dev-server to dependencies
  Adding webpack-manifest-plugin to dependencies
  Adding workbox-webpack-plugin to dependencies

Updating the scripts
  Replacing "react-scripts start" with "node scripts/start.js"
  Replacing "react-scripts build" with "node scripts/build.js"
  Replacing "react-scripts test" with "node scripts/test.js"

Configuring package.json
  Adding Jest configuration
  Adding Babel preset

Running npm install...

up to date, audited 1418 packages in 2s

185 packages are looking for funding
  run `npm fund` for details

5 high severity vulnerabilities

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.
Ejected successfully!

fatal: not a git repository (or any of the parent directories): .git
Staged ejected files for commit.

Please consider sharing why you ejected in this survey:
  http://goo.gl/forms/Bi6CZjk1EqsdelXk1

接下來啟動它。

npm run start

此時服務會默認為即時加載,若在源文件有任何的修改,都會立即反應,無需手動刷新頁面。

集成react與django

如何使用django來顯示react呢?,我們使用django內建的命令,工作原理如下:

1. 使用django默認靜態支持

請參閱django文檔,主要設置有:
– STATICFILES_DIRS
– STATIC_URL
– STATICFILES_STORAGE-ManifestStaticFilesStorage用於讓 Django 散列文件名以實現可緩存性。

2. 配置Webpack寫入文件到STATICFILES_DIRS

使用任何你喜歡的 Webpack 配置,但只有幾個設置很重要:

1. 讓 Webpack 寫入目錄STATICFILES_DIRS
2. 配置output.publicPath以匹配 Django 的STATIC_URL
3. Don’t let Webpack hash filenames (except for chunks, see below)
4. Make sure webpack-dev-server writes files to disk (so Django can serve them in development)
// Relevant parts of webpack.config.js
output: {
  path: path.resolve(__dirname, "myapp/static"), // Should be in STATICFILES_DIRS
  publicPath: "/static/", // Should match Django STATIC_URL
  filename: "[name].js", // No filename hashing, Django takes care of this
  chunkFilename: "[id]-[chunkhash].js", // DO have Webpack hash chunk filename, see below
},
devServer: {
  writeToDisk: true, // Write files to disk in dev mode, so Django can serve the assets
},

現在可以在開發的過程中,同時執行webpack-dev-server與django服務。webpack會將文寫入STATICFLES_DIR。

要使用webpack生成的文件,只要使用django static的模版即可:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'app.css' %}">
<script type="text/javascript" src="{% static 'app.js' %}"></script>

對於生產及部署,只要先讓webpack先建構文件,然後使用python manage.py collectstati即可生成django所需react的文件,即簡單又實用。

webpack的動態導入

webpack散列塊文件很重要,默認情況webpack會在運行時使用數字塊ID來引用,當django collectstatic運行,它會對文件名進行hashing處理,然後在其他文件中查找未哈希處理的引用來替換它們。

例如,如果您有一個引用文件的樣式表foo.jpg並且 Django 重命名foo.jpg為foo.695e1b313f34.jpg,它將替換foo.jpg樣式表中的引用為foo.695e1b313f34.jpg.

chunk id默認情況下,Webpack 在運行時通過數字引用塊,collectstatic因此無法正確識別塊文件名。通過讓 Webpack 散列塊文件名,我們得到正確散列的塊文件名,因此這些文件可以被瀏覽器正確緩存。

參考

將 Webpack 與 Django 一起使用:無需插件!
在Django中使用Webpack:再也不需要插件了!
Modern Django: Part 1: Setting up Django and React
从零开始创建react+Django项目
Webpack 簡介[筆記][React]從零到一的webpack開發環境(1)-安裝執行篇
如何讓Django和ReactJS一起工作?
React 教程:概述和演练
用DJANGO-WEBPACK-LOADER实现DJANGO和WEBPACK的绑定

發佈留言