js开发历史
https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70
基本用法
npm install webpack-cli webpack --save-dev
./node_modules/.bin/webpack index.js --mode=development # development: code is readable, production: code is compressed
# 运行webpack会将所有的服务端代码,包含require语句,转换成浏览器代码,输出到dist/main.js
注:webpack负责require的转换,而babel负责import的转换.
webpack.config.js
每次都手动运行webpack指定参数是繁琐的,因此通过webpack.config.js来配置
// webpack.config.js
module.exports = {
mode: 'development',
entry: './index.js',
output: {
filename: 'main.js',
publicPath: 'dist'
}
};
然后运行
./node_modules/.bin/webpack
在webpack中使用babel
npm install @babel/core @babel/preset-env babel-loader --save-dev
babel-loader
用于与webpack交互,@babel/preset-env
用于指定js特性集合
// webpack.config.js
module.exports = {
mode: 'development',
entry: './index.js',
output: {
filename: 'main.js',
publicPath: 'dist'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};
热加载
npm install webpack-dev-server --save-dev
{
"name": "modern-javascript-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --progress -p",
"watch": "webpack --progress --watch",
"server": "webpack-dev-server --open"
},
"author": "",
"license": "ISC",
"dependencies": {
"moment": "^2.19.1"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"babel-loader": "^8.0.2",
"webpack": "^3.7.1",
"webpack-dev-server": "^3.1.6"
}
}
watch
当文件发生变化时,自动编译文件
webpack-dev-server
自动打开index.html