Posts Tagged ‘js sdk’
ES6 modules & classes with Webpack: quick setup & usage
For setting up and using ES6 Modules with webpack perform the following steps:
- quicky setup js-sdk library using webpack
- Install babel-loader and its dependencies.
npm install babel-loader babel-core babel-preset-env --save-dev
Here babel-loader is the main package for invoking Babel transpilation. It requires babel-core for apis. babel-presets has the plugin for module-loading.
- Configure webpack.config.js
vi index.js
//Class definition export default class Imax { get movies() { return ['Logan', 'Beauty and the Beast']; } bookMovie(name) { return `Thank you for booking with Imax. Booking ID is ASDFFG|${name}`; } } module.exports = new Imax();
- webpack // build library
- webpack-dev-server // host library. (hosted locally here)
- Client side:
$.getScript('//localhost:8080/assets/imax.js').then(() => { let selectedMovie = Imax.movie[0]; console.log('Movie list: ', Imax.bookMovie(selectedMovie)); });
- O/P:
Thank you for booking with Imax. Booking ID is ASDFFG|Logan
References:
- http://www.ecma-international.org/ecma-262/6.0/
- https://github.com/babel/babel-loader
- http://es6-features.org/
Advertisements
Quickly setup JS SDK library using Webpack
Technology used:
- node version : 6.9.4
- npm version : 3.8.5
- webpack : 2.2.1
- webpack-dev-server : 2.4.1
Steps:
mkdir imax
//project namecd imax
npm init
npm install webpack --save-dev
npm install webpack-dev-server --save-dev
//for development use only
webpack-dev-server
helps serve the webpack bundle.vi index.js
module.exports = { greetings: 'Welcome to IMAX movie booking', movies: ['Logan', 'Beauty and the Beast', 'Transformers'] }
- Now on running
npm run build
, the following error occurs,No configuration file found and no output filename configured via CLI option. A configuration file could be named 'webpack.config.js' in the current directory. Use --help to display the CLI options.
webpack requires webpack.config.js file.
vi webpack.config.js
module.exports = { entry: './index.js', //app entry point output: { path: 'dist', //output directory absolute path publicPath: '/assets/', //public URL address of output files filename: 'imax.js', //output-bundle filename library: 'Imax' //helps export output-bundle as library } }
The configuration is done. Now execute the below commands,
npm run build
It internally invokeswebpack,
which compiles & bundles the library file.npm start
It starts the dev server & serves the bundled file athttp://localhost:8080/assets/imax.js
Client side JS:
$.getScript('//localhost:8080/assets/imax.js').then(() => { console.log(Imax.greetings); console.log('Movie list: ', Imax.movies); });
You can also directly add the script in html and use the library functions.
Output:
Welcome to IMAX movie booking Movie list: ['Logan', 'Beauty and the Beast', 'Transformers']
References: