# \[WEBPACK] Dùng webpack để sử dụng từ khóa import, export (ok)

package.json

```
{
  "name": "abc",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "dependencies": {
    "webpack": "^4.42.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack -p",
    "watch": "webpack --watch"
  },
  "author": "",
  "license": "ISC"
}

```

{% embed url="<https://webpack.config.js>" %}

```
var path = require('path');
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname)
  }
};
```

{% embed url="<https://index.js>" %}

```
//src/index.js
const sum = require('./math');
const total = sum(1,5);
console.log(total);
```

math.js

```
//src/math.js
const sum = (a,b) => {
	return a + b;
}
module.exports = sum;
```

index.html

```
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<script src="bundle.js"></script>
</body>
</html>
```

## Các bước thực hành

```
$npm init
$npm install -g webpack
// Thay đổi package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack -p",
    "watch": "webpack --watch"
},
// webpack.config.js
var path = require('path');
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname)
  }
};
$npm i -g webpack-cli
$webpack
```

Bài 2: Babel

```
npm install --save-dev babel-loader babel-core babel-preset-env
```

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1E4Gk2ppVKb4olmnun%2F-M38KAovIt9jOryLQDYR%2F-M38Ky6XOl2qq83w71Ja%2FScreenshot_2.png?alt=media\&token=031fde7e-9702-499d-bacc-ca0912d7b0a3)

webpack.config.js

```
var path = require('path');
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'build')
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/
      }
    ]
  }
};
```

Mẫu hoàn chỉnh sử dụng được luôn ES6 && ReactJS

{% file src="<https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1E4Gk2ppVKb4olmnun%2F-M38L9NdM6FUliTELam9%2F-M38dA0kfBRFbb4tCvR-%2Ftest.rar?alt=media&token=f9adaebd-1030-43b2-869e-32622e836938>" %}
