Showing posts with label webpack. Show all posts
Showing posts with label webpack. Show all posts

5/5/20

Dont Afraid To Use Webpack

I must admit - im afraid of configuring the webpack by myself.
Im usually use create-react-app or angular-cli or some other boilerplate projects that have webpack configured already...
So the purpose of this post is: to create the simpliest configuration of webpack ever.
But first we need to ask - what is the main purpose of webpack anyway?
According to their site - webpack is module bundler Which means: a tool which concats all javascript modules (or files) into one big file. (that's all).

Experiment number one

Lets install webpack and play a little:

npm i -D webpack webpack-cli

Here is our first the webpack.config.js file:

const path = require('path');

module.exports = {
  entry: './myfile.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
};

At myfile.js lets put some very complicated code:

console.log('Hi@!')

And now lets run npx webpack

You can see that 'my-first-webpack.bundle.js' file created at 'dist' directory (wow!)
Note that it is minified and uglyfied (which is good...)

Experiment 2

Now - to something little more complicate: lets create another file, name it "other.js" and import it from the 'myfile':
other.js


export default Other = () => {
  console.log('Hi@!')
}

Again, run npx webpack
and we got only one 'my-first-webpack.bundle.js' in the dist (and yes it contains 'console.log' statement)

Experiment 3

Ok, you may say, but... how this webpack thing can help me with using some external library like, say React?
The answer is: lets try and see:

npm i react react-dom

Now lets change our myfile.js code to:

import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
  return React.createElement("div", {}, 'Hi!');
};
ReactDOM.render(React.createElement(App), document.getElementById("root"));

run npx webpack
Now create index file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    <script src="dist/my-first-webpack.bundle.js"></script>
</body>
</html>

double click it and... whoale!
We can see our React app is running

11/17/16

Organizing Your Angularjs Typescript Project

In one of my previous posts i found how to compile typescript files to javascript and i was very happy with myself because of my success. Since then i had little more experience with typescript. And now i have a few more points to share:

Using Import In Your Typescript Project

I have noticed many angularjs and angular2 projects using Import syntax. That way they not need to compile each file separately, instead you can compile only main file while all other files included in it (like in less or sass)
For exapmle :
Instead put all the things in your JS app.js file


//OOOOOLD STUFF.. BLAHHH
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

In typescript, you can move the config logic to its own separate config.ts file:

 export function config($locationProvider: ng.ILocationProvider, $routeProvider: angular.route.IRouteProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.otherwise({redirectTo: '/view1'});
  };



and import it to app.ts main file:

/// 
import { config } from './config';///<--HERE
module angularSeed {
'use strict';

  // Declare app level module which depends on views, and components
  angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.version'
  ]).config(config)

}
 

Import Is ES6 Syntax (Not Typescript!)

So, if you need to transpile your code either from ES6 and from typescript - i cannot think about other tool than webpack.

Weeeebpaaaack....
Webpack supports ES6 natively and for get it to compile typescript you only need to include ts-loader:
 
var webpack = require('webpack');
var path = require('path');
module.exports = {
    context: path.join( __dirname, '/app'),
    entry: 'app.ts',
    output: {
        filename: 'app.js',
        path: path.join( __dirname, '/app')
    },
    resolve: {
        root: path.join( __dirname, '/app'),
        extensions: ['', '.ts', '.webpack.js', '.web.js', '.js']
    },
    module: {
        loaders: [//<-- TYPESCRIPT, COOOL
        // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.ts?$/, loader: 'ts-loader' }
        ]
    }
}

Of course you need to include this webpack.config.js file in your project And update package.json with too more entries:
 
    "typings": "^0.8.1",
    "webpack": "1.13.1",
 

Build The Project

Since we using webpack now for build the project, the command to compile will be:


node_modules/.bin/webpack
 

Hope you have fun reading...
Visit my cool REPO

8/16/16

React - Organizing the project

How To Organize the Project

Yes, we created little app using the react library. For simplicity i used (already removed in latest babel version) browser module of babel-core which compiles the react in the browser. Thats not ideal way of writing react aps(compiling in the browser is heavy operation that can be done using some task running tool instead).

Using Webpack

There are many tools which can do the react compilation job. One of those tools is a well known webpack which we will use for this post

Installing Webpack

For be able to run webpack you must have nodejs installed on your machine.
Lets run this command in the console for install webpack globally


   npm install webpack -g
Now you able to bundle your javascript files into one js file named "bundle.js" with single console command

webpack ./app.js app.bundle.js
Instead of specify parameters in the command line, better attitude is to specify them in wepack.config.js file:

 module.exports = {
     entry: './src/app.js',
     output: {
         path: './bin',
         filename: 'app.bundle.js'
     }
 };
Tha way the command is way more shorter:

webpack //thats it

Dependencies

Since we will create react application we will need to install various dependencies (like babel) which will help us to compile and run our project. It is good practice to store list of dependencies in package.json file, so npm module of nodejs will be able to install them at once using single command npm install.
For creating package.json file run:


npm init 
Will promp you with various questions about your project, currently you may answer "yes" (by pressing ENTER) on all of them. finally package.json file will be created in your root directory.
From now each module we will install - will be listed in the package.json file:

 npm i react react-dom --save
package.json :

{
  "name": "webpack project",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.3.0",
    "react-dom": "^15.3.0"
  }
}

babel

Since react contains some features that not supported by some browsers (like jsx) we will use babel library:


npm install --save-dev babel-loader babel-core babel-preset-react
So our wepack.config.js file will finally look like:

 module.exports = {

     entry: './src/app.js',
     output: {
         path: './out',
         filename: 'app.bundle.js',
     },
     module: {
         loaders: [{
             test: /\.js?|\.jsx?$/,
             exclude: /node_modules/,
             loader: 'babel',
             query: {
                presets: ['react']
             }             
         }]
     }
 }
Now our project configured in the way so when user runs

webpack
command in the console-
it compiles every javascript (.js) file and it puts the results inside out directory in single file app.bundle.js, isnt that cool?

Project Structure

After we created the minimalistic configuration, lets take a care about files that are part the project itself:
app.js file where we will place our (need to be compiled) javascript code (lets put it in the "src" directory) and index.html - the main html file of our single page app which will refer the compiled results of javascript:


 <!DOCTYPE html>
 <html>
     <head>
         <meta charset="utf-8">
     </head> 
     <body>
         <div id="example"></div> 
         <script  src="out/app.bundle.js" charset="utf-8"></script>
     </body>
 </html>
Now lets paste the app code into the app.js file

var React = require('react');
var ReactDOM = require('react-dom');
var $ = require("jquery");

//Search Bar
var SearchBar = React.createClass({
  
  onChange: function(e) { 
    // console.log(e.target.value)
    this.props.onTextChange(e.target.value);
  }, 
  render: function() {
    return (
      <div><input placeholder="type search term" onChange={this.onChange}/></div>
    );
  }
});   
// Results List
var ResultsList = React.createClass({

  render: function() {
    
      var createItem = function(item, idx) {
        return <li key={idx}>{item.text}</li>;
      };
      var list;
      if(this.props.results && this.props.results.length && !this.props.loading) {
        list = this.props.results.map(createItem);
      } else if(this.props.results.length==0  && !this.props.loading){
        list = 'no items yet';
      } else if(this.props.loading) {
        list = <div className="loader">Loading...</div>;
      }
      return <ul className="results">{list}</ul>;
    
  }
});
//Search Page
var SearchPage = React.createClass({
  getInitialState: function() {
    return {results: [],loading:false};
  }, 
  loadResults: function(query){
    this.setState({loading:true});
    
    var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
    $.get(url)
    .then(function (result) {
      
      if(result.items.length!==0){ 
        var results = result.items.map(item => { 
          return   {text: item.name}
        }).slice(0,5);
        
      }
      this.setState({loading: false, results:results});
    }.bind(this));//<-- important to bind this for use "setState"
    
  },
  handleSearchTextChange: function(txt){

    this.loadResults(txt)
    
  },
  render: function() {
    return (
      <div>
        <SearchBar onTextChange={this.handleSearchTextChange}/>
        <ResultsList results={this.state.results}  loading={this.state.loading}/>
      </div>
    );
  }
});
    
ReactDOM.render(
    <SearchPage />,
    document.getElementById('example')
);
module.exports = SearchPage;

jquery

the last thing left is to add jquery library to the project


 npm install --save jquery 
After jquery is included and project compiled you can run it with

webpack-dev-server
The developer server of webpack.
Here is link to repo with the code.
Hope you have fun reading

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...