[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"
}
var path = require('path');
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname)
  }
};
//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

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

Last updated

Navigation

Lionel

@Copyright 2023