wagtail で
wagtail + django-webpack-loader + react で
[TOC]
前提
以下の
OS
% sw_vers ProductName: Mac OS X ProductVersion: 10.13.1 BuildVersion: 17B1003
Python の
Version % python3 -V Python 3.6.2
Django の
Version % python3 -m pip list --format=columns | grep Django Django 1.11.8
事前環境構築と
* Django プロジェクトを
最終的な ディレクトリ構成
インストール、
├── assets // jsファイルの配置先 │ ├── js │ └── webpack_bundles ├── home // django app ├-- db.sqlite3 ├-- manage.py ├-- node_modules ├-- package-lock.json ├-- package.json ├-- requirements.txt ├-- webpack-stats.json ├-- webpack.config.js └── mysite // django project app
雛形作成の 流れ
雛形作成の
webpack、
react の インストール、 設定 django-webpack-loader を
インストール、 設定 雛形ページの
作成
1. webpack、 react、 babel の インストール、 設定
webpack の インストール、 設定
- インストール
webpackをつかって djangoで bootstrap4を はじめる - Qiita を 参考に、 webpack の インストールを 実施します。
django のプロジェクトルートフォルダに 移動し、 以下の コマンドを 実行します。 npm init -f npm install --save-dev webpack webpack-bundle-tracker
webpack.config.js の 作成
django のwebpack.config.js
を
var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, /* エントリーポイント */ entry: './assets/js/main.js', output: { path: path.resolve('./assets/webpack_bundles/'), filename: "[name]-[hash].js" }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}) ] }
エントリポイントの 作成
エントリポイントは、./assets/js/main.js
です。
ディレクトリと、
エントリポイントが
エントリポイント · JavaScriptの
現在(2018/01/18)の
エントリポイントとは、
アプリケーションの 中で 一番最初に 呼び出される 部分の ことです。 アプリケーションを 作成するに あたり、 まずは エントリポイントを 用意しなければなりません。 Webアプリケーションに おいては、 常に HTMLドキュメントが エントリポイントと なります。 ウェブブラウザに よりHTMLドキュメントが 読み込まれたあとに、 HTMLドキュメント中で 読み込まれたJavaScriptが 実行されます。
mkdir -p assets/js touch assets/js/main.js
js ファイルの ビルド
webpack の
js ファイルを
./node_modules/.bin/webpack --config webpack.config.js ------------------------------------------ Hash: 315df4b2f5abf7716c38 Version: webpack 3.10.0 Time: 69ms Asset Size Chunks Chunk Names main-315df4b2f5abf7716c38.js 2.47 kB 0 [emitted] main [0] ./assets/js/index.js 0 bytes {0} [built] ------------------------------------------
react、 babel の インストール、 設定
Reactを
react の インストール
django の
npm install --save react react-dom
Babel 関連の パッケージの インストール
babel の
npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-es2015
.babelrc の 作成
vi .babelrc ----------------------------------- { "presets": ["react", "es2015"] } -----------------------------------
webpack.config.js の 修正
babel、
var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, /* エントリーポイント */ entry: './assets/js/main.js', output: { path: path.resolve('./assets/webpack_bundles/'), filename: "[name]-[hash].js" }, /* ソースマップをファイル内に出力させる場合は以下を追加 */ devtool: 'inline-source-map', module: { /* loaderの設定 */ loaders: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, // 除外するファイル/ディレクトリ(正規表現可) loader: 'babel-loader' // 使用するloader } ] }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}) ] }
npm コマンドの 登録
package.json
に
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "watch": "./node_modules/.bin/webpack --watch --progress", "build": "./node_modules/.bin/webpack --config webpack.config.js" },
上記コマンドの
npm run watch npm run build # これは`package.json` 追加後、デフォルトで定義されているコマンドになります。 npm run test
以上で、
2. django-webpack-loader を インストール、 設定
続いて、
django-webpack-loader の インストール
pip で
python3 -m pip install django-webpack-loader ------------------------------------------- Collecting django-webpack-loader Downloading django_webpack_loader-0.5.0-py2.py3-none-any.whl Installing collected packages: django-webpack-loader Successfully installed django-webpack-loader-0.5.0 -------------------------------------------
STATICFILES_DIRS の 作成 と 設定
django のstatic
で、
STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), ]
これを、README.md
のassets
に
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets'), os.path.join(PROJECT_DIR, 'static'), ]
settings.py に WEBPACK_LOADER
を 追加する
以下も、README.md
の
settings.py にWEBPACK_LOADER
を
WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'webpack_bundles/', # must end with slash # PROJECT_DIRからここは変えているかもしれません。 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': ['.+\.hot-update.js', '.+\.map'] } }
INSTALL_APPS に webpack_loader
を 追加する
settings.py のwebpack_loader
を
INSTALLED_APPS = [ ... 'webpack_loader', ]
動作確認用の ため、 template に js 読み 込み 記述を 追加
テンプレートファイルに
{% load render_bundle from webpack_loader %} {# 以下は、body タグの直前に #} {% render_bundle 'main' %}
サーバー起動して、 動作確認
サーバーを
python3 manage.py runserver
http://127.0.0.1:8000
に{% render_bundle 'main' %}
が、<script type="text/javascript" src="/static/webpack_bundles/main-315df4b2f5abf7716c38.js"></script>
に3. 雛形ページの 作成
react の
mzabriskie/react-example: Simple React example app を
必要なApp.jsx
と、main.js
に
wagtail helloword
を
* assets/js/App.jsx
import React from 'react'; class App extends React.Component { render() { return ( <div>wagtail, helloworld</div> ); } } export default App;
- assets/js/main.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App />, document.getElementById('app'));
発生した エラー
インストール、
Module parse failed: Unexpected token (6:6)
React の
ERROR in ./assets/js/App.jsx Module parse failed: Unexpected token (6:6) You may need an appropriate loader to handle this file type.
JSX is not transform by babel loader from node_modules/my_module · Issue #377 · babel/babel-loader
コンパイルする
webpack.config.js
に、jsx
のmodule: { /* loaderの設定 */ loaders: [ { test: /\.(js|jsx)$/, // jsxも対象にする exclude: /node_modules/, // 除外するファイル/ディレクトリ(正規表現可) loader: 'babel-loader' // 使用するloader } ] },
Target container is not a DOM element.
画面表示時に
Target container is not a DOM element.
OSError: Error reading /Users/xxxxx/xxxx/webpack-stats.json.
Django の
OSError: Error reading /Users/xxxxx/xxxx/webpack-stats.json. Are you sure webpack has generated the file and the path is correct?
One of the core principles of django-webpack-loader is to not manage webpack itself in order to give you the flexibility to run webpack the way you want. If you are new to webpack, check one of the examples, read my detailed blog post or check webpack docs.
django-webpack-loader
は
webpack の
補足
django * react の
ひと
Create React App and Django
どちらかと
次回構築する
以上です。
README.md
には、npm install --save-dev webpack-bundle-tracker
の記載が ありますが、 インストール先の 調整が 必要に 思いましたので、 とばしています。 ↩
コメント