一直对webpack的理解没有那么深,或者说只有真的用了webpack才会记得比较清楚,在github上把webpack的全部Guide内容都运行了一遍,每一个部分作为一个分支,均可以正常打包运行。应该还会不断的更新新的内容,补充一下webpack的知识。
github上Guide的代码地址
webpack官网地址
webpack中文官网地址
webpack官网翻译的部分内容
当前webpack 的最新稳定版本为 3.10.0。
Hello World!
当前项目是一个空文件夹,在项目根目录的命令行中执行:yarn add -D webpack,将会生成与 webpack 相关的必要文件。
- 在项目根目录下新建 src 文件夹用于存放源文件。
- 新建 src/index.html
//src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
- 新建 src/index.js
// src/index.js
console.log("Hello World!");
- 新建 webpack.config.js
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'src')
}
};
- 项目根目录命令行下执行:webpack,在 src 文件夹下生成 bundle.js 文件,用浏览器打开 src/index.html,可以在浏览器的命令行中看到 Hello World! 输出。
将编译结果移动至 dist 文件夹
- 删除之前编译生成的 src/bundle.js。
- 项目根目录命令行下执行:
yarn add -D clean-webpack-plugin
yarn add -D html-webpack-plugin
- 修改 webpack.config.js
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
})
]
};
- 删除 src/index.html 中
<script src="bundle.js"></script>
这一行,html-webpack-plugin 插件将自动为我们创建这一行对应的内容。
webpack-dev-server
- 在项目根目录的命令行中执行:
yarn add -D webpack-dev-server
。 - 在项目根目录的命令行中执行:
node_modules/.bin/webpack-dev-server
,可以进入 webpack 的开发者模式。
npm 脚本
在 package.json 中添加:
{
...
"scripts": {
"build": "webpack",
"start": "node_modules/.bin/webpack-dev-server"
}
...
}
在项目根目录的命令行中可以使用 yarn build 代替 webpack 进行编译;可以使用 yarn start 代替 node_modules/.bin/webpack-dev-server 进入开发者模式。
用 typescript 代替 javascript 进行开发
- 在项目根目录的命令行中执行:
yarn add -D typescript ts-loader
安装必要的包。 - 在项目根目录下新建 tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
- 将 src/index.js 修改成 src/index.ts。
- 修改 webpack.config.js
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
})
],
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};