function.phpに記述する内容に、CDNからReactのスクリプトを読み込むことができていないと、Uncaught TypeError: Cannot read properties of undefined (reading ‘createRoot’)と叱られる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php function my_react_theme_enqueue_scripts() { // React と ReactDOM(UMD形式)をCDNから読み込む wp_enqueue_script( 'react', 'https://unpkg.com/react@18/umd/react.development.js', array(), '18.0.0', true ); wp_enqueue_script( 'react-dom', 'https://unpkg.com/react-dom@18/umd/react-dom.development.js', array('react'), '18.0.0', true ); // Reactアプリ本体(build/index.js) wp_enqueue_script( 'my-react-theme-script', get_template_directory_uri() . '/build/index.js', array('react', 'react-dom'), filemtime(get_template_directory() . '/build/index.js'), true ); } add_action('wp_enqueue_scripts', 'my_react_theme_enqueue_scripts'); |
さらに、Cannot read properties of undefined (reading ‘jsx’)と叱られたら、CDN から読み込んだ UMD 版の React(および ReactDOM)に、react/jsx-runtime のエクスポートが含まれていないために変換後のコードが参照する「jsx」が未定義ということらしい。そこで、babel.config.jsをつくって、クラシックモードにするように記述する
1 2 3 4 5 6 7 8 9 10 11 |
module.exports = { presets: [ [ '@babel/preset-react', { runtime: 'classic' // これで自動変換を無効にして classic モードに } ], '@babel/preset-env' ] }; |
コメント