Loading repository data…
Loading repository data…
reecerussell / repository
A brief and basic example on using Webpack and Babel to transpile modern JavaScript to more browser-friendly ES5 JavaScript.
A brief and basic example on using Webpack and Babel to transpile modern JavaScript to more browser-friendly ES5 JavaScript.
npm init -y
npm i webpack webpack-cli babel-loader @babel/preset-env @babel/core -D
webpack.config.js.webpack.config.js, and do something like this:const path = require("path");
module.exports = {
entry: "./src/index.js", // This is your entrypoint file.
mode: "production",
output: {
filename: "index.js", // The name of your output file.
path: path.resolve(__dirname, "dist"), // The output directory.
// This field is only really needed when you're consuming your
// package in ES6/7.
libraryTarget: "commonjs2"
},
module: {
rules: [
{
test: /\.js$/, // This targets all files with the .js extension.
exclude: /node_modules/, // Ignore the node_modules directory.
loader: "babel-loader", // This specifies that we want to use babel.
// Loader options for the babel-loader.
options: {
// Presets tell Babel how to transpile your code.
presets: ["@babel/preset-env"],
// This is optional, but allows Babel to transpile class properties.
plugins: ["@babel/plugin-proposal-class-properties"]
}
}
]
}
};
package.json file. In the root of the JSON, there should be a "scripts" object - if there isn't, you'll need to create one. In the "scripts" object, add a new string called "webpack" (this can be called anything), and set the value to "webpack". For example:{
"scripts": {
"webpack": "webpack"
}
}
class MyClass {
constructor() {
this._prefix = "MyClass:";
}
Print = text => {
console.log(`${this._prefix} ${text}`);
};
}
export default MyClass;
npm run webpack
Once complete, there should be a new file in your dist directory with your transpilled code.
So how can you use React with your new setup? There are two simple steps:
npm i react @babel/preset-react -D
{
test: /\.js$/, // This targets all files with the .js extension.
exclude: /node_modules/, // Ignore the node_modules directory.
loader: "babel-loader", // This specifies that we want to use babel.
// Loader options for the babel-loader.
options: {
// Presets tell Babel how to transpile your code.
presets: ["@babel/preset-env", "@babel/preset-react"],
// This is optional, but allows Babel to transpile class properties.
plugins: ["@babel/plugin-proposal-class-properties"]
}
}
That's it. Now you can use JSX and React in your classes. For example:
import React from "react";
class MyClass {
constructor() {
this._prefix = "MyClass:";
}
Print = text => {
console.log(`${this._prefix} ${text}`);
return (
<p>
{this._prefix} {text}
</p>
);
};
}
export default MyClass;
Last updated: 6th November 2019
By: Reece Russell