I've used Webpack to bundle all my npm modules. Here's my webpack.config.js:
"use strict";
module.exports = {
entry: './main.js',
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{test: /\.json$/, loader: "json"},
]
},
};
Here's the main.js I refer to. As you can see, I try to import React, React-dom, fixed-data-table, chartjs, jquery and visjs.
import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
import Chart from 'chartjs';
import jquery from 'jquery';
import vis from 'vis';
All is good, and I remoce the react, chartjs, jquery etc. src from my index.html and just refer to the newly created bundle.js altogether.
In my functional .js file where content is derived from, and my react classes are, I add the following to the beginning(where I assume the error stems from)
import React from './bundle';
import ReactDOM from './bundle';
import {Table, Column, Cell} from './bundle';
import Chart from './bundle';
import vis from './bundle';
This results in my browser dev tools giving me the error: Uncaught Referenceerror: React is not defined.
Where did I go wrong in the bundling process? I'm assuming the bundling went fine since there were no errors. But how do I import, for example, React in another .js file properly?
Here's my package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.3.17",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-runtime": "^6.3.19",
"chartjs": "^0.3.24",
"webpack": "^1.12.9"
},
"dependencies": {
"chartjs": "^0.3.24",
"fixed-data-table": "^0.6.0",
"react": "^0.14.3",
"react-dom": "^0.14.3",
"vis": "^4.17.0"
}
}
Webpack will start from './main.js'
and read import
statement to determine the modules need to bundle.
webpack concept
Update:
Since the library already in bundle.js, your files should look like this :
Index.html(do not include any library already import in .js file you write)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
main.js :
import React from 'react';
....
You can't import from 'bundle.js', because it is compiled to ES5 and ES5 don't support modules (imports and exports).
Properly way to import React to another js is via import
import React from 'react'
You can find more info about Modules at: https://www.sitepoint.com/understanding-es6-modules/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With