Reputation: 153
I have differents JSfiles and I have to use Babel to create a single JS bundle.
They recommended me this 1st link, but I don't understand how to: https://babeljs.io/docs/usage/cli/
Browsing in the internet I found this 2nd link: http://ccoenraets.github.io/es6-tutorial-data/babel-webpack/ which obligates me to use this third one first: http://ccoenraets.github.io/es6-tutorial/setup-babel/
Are 2nd and 3rd links a viable form for learning how to create a single JS bundle? Is there any other good and easy option?
Upvotes: 5
Views: 6183
Reputation: 1113
I am not sure if you can use babel as a bundler. However since you are new, I suggest looking in to webpack. If this is an option, read on
Your folder structure can be initially something similar to below
project folder
|
|-src
| |
| |- index.js
| |- moduleOne.js
| |- moduleTwo.js
|
|- index.html
|- webpack.config.js
index.html
<!doctype html>
<html>
<head>
<title>Sample</title>
</head>
<body>
content
<script src="dist/bundle.js"></script>
</body>
</html>
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
moduleOne.js
export default class moduleOne {
constructor() {
console.log('moduleOne constructor');
}
someFunc(text){
console.log(text);
}
}
moduleTwo.js
export default class moduleTwo {
constructor() {
console.log('moduleTwo constructor');
}
someFunc(text){
console.log(text);
}
}
on a command line window, navigate to project folder and type npm install webpack --save-dev
then run webpack
to bundle files. This will create a dist
folder with bundle.js
file in it.
Now if you open the index.html
on browser, you should see following console output.
moduleOne constructor
moduleTwo constructor
moduleOne.someFunc
moduleTwo.someFunc
In a nutshell, index.js
imported moduleOne.js
and moduleTwo.js
, instantiated them and called the someFunc()
method. Webpack bundled all this in to dist/bundle.js
. This is a quick setup but hopefully you'll get the idea
Source: webpack
Upvotes: 7