Reputation: 6137
I'm trying to add React to an existing Symfony4 project with Webpack Encore ; I followed guides around, and that looked pretty straightforward... But I'm keep getting an exception saying "React is not defined", can't do anything.
Here are the files :
webpack.config.js
var Encore = require('@symfony/webpack-encore')
// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev')
}
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or sub-directory deploy
//.setManifestKeyPrefix('build/')
// React
.enableReactPreset()
.addEntry('react-app', './assets/react-app/index.js')
// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()
// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()
/*
* FEATURE CONFIG
*
* Enable & configure other features below. For a full
* list of features, see:
* https://symfony.com/doc/current/frontend.html#adding-more-features
*/
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
// enables @babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage'
config.corejs = 3
})
.configureBabel(function (babelConfig) {
babelConfig.plugins = [
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-transform-runtime',
]
})
module.exports = Encore.getWebpackConfig()
index.js
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
)
in base.html.twig
{{ encore_entry_script_tags( 'react-app') }}
Am I missing something ?
(Btw, I have a in my template to call React)
Keep getting this error :
Uncaught ReferenceError: React is not defined
at Module../assets/react-app/index.js (index.js:5)
at __webpack_require__ (bootstrap:79)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at react-app.js:1
EDIT: if I had 'window.React = React' right after the import (as I saw in other topics), it works... Is it a normal thing ?
Upvotes: 1
Views: 1139
Reputation: 91
you need to import react in your index.js file like this :
import React from 'react'
Upvotes: 2