In my Django template, I am loading React via CDN and also loading the index.js
script from static url where the React code lives:
<!DOCTYPE html>
<html>
{% load static %}
<head>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
</head>
<body>
<div id="root"></div>
</body>
<script src="{% static 'react/js/index.js' %}" type="text/babel"></script>
</html>
Index.js is:
class App extends React.Component {
constructor() {
super()
}
render() {
return <div>App</div>
}
}
ReactDOM.render(<App />, document.getElementById('root'))
This works fine. But I also have helpers.js
script sitting in the same static
directory as index.js
and if I try to import something from it in index.js
:
import { some_helper } from './helpers.js'
class App extends React.Component { ...
I get
ReferenceError: require is not defined
error in the browser console.
I could change the script type to module
to make import/export work, but then React would not work. So instead I included require
over CDN in index.html
:
<!DOCTYPE html>
<html>
{% load static %}
<head>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
</head>
but then I get the following error in the console:
Error: Module name "helpers.js" has not been loaded yet for context: _. Use require([]) https://requirejs.org/docs/errors.html#notloaded
and I don't know how to move on from there.
Could someone guide me how to have make both React and import/export work in a single JS file?
If this is not an issue, I'd rather stick with loading React over CDN.