// Exporting
export const myFunction = () => { /*...*/ };
// Importing
import { myFunction } from './myModule.js';
// Exporting
module.exports = myFunction;
// Importing
const myFunction = require('./myModule');
<script type="module">
to enable ES modules <script type="module" src="app.js"></script>
node -v
npm -v
npm init -y
package.json
file npm install axios
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => console.log(response.data));
Why Use Bundlers?
Popular Bundlers
npm install webpack webpack-cli --save-dev
webpack.config.js
: const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
mode: 'development',
};
package.json
: "scripts": {
"build": "webpack"
}
npm install css-loader style-loader --save-dev
webpack.config.js
: module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
```
3. Import CSS in JavaScript:
```javascript
import './styles.css';
```
npm install html-webpack-plugin --save-dev
const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
npm install webpack-dev-server --save-dev
webpack.config.js
: devServer: {
contentBase: './dist',
open: true,
},
package.json
: "scripts": {
"start": "webpack serve --open",
"build": "webpack"
}
```"""
npm install @babel/core babel-loader @babel/preset-env --save-dev
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
],
},
src/
├── index.js
├── utils.js
└── components/
├── header.js
└── footer.js
// utils.js
export function capitalize(str) {
return str.toUpperCase();
}
// index.js
import { capitalize } from './utils';
Production Build:
Deployment Platforms:
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from './math';
console.log(add(2, 3)); // Output: 5
// components/index.js
export { Header } from './header';
export { Footer } from './footer';
// Usage
import { Header, Footer } from './components';