一直对webpack的理解没有那么深,或者说只有真的用了webpack才会记得比较清楚,在github上把webpack的全部Guide内容都运行了一遍,每一个部分作为一个分支,均可以正常打包运行。应该还会不断的更新新的内容,补充一下webpack的知识。
github上Guide的代码地址
webpack官网地址
webpack中文官网地址
当前webpack 的最新稳定版本为 3.10.0。
当前项目是一个空文件夹,在项目根目录的命令行中执行:yarn add -D webpack,将会生成与 webpack 相关的必要文件。
//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
console.log("Hello World!");
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'src')
}
};
yarn add -D clean-webpack-plugin
yarn add -D html-webpack-plugin
// 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'
})
]
};
<script src="bundle.js"></script>
这一行,html-webpack-plugin 插件将自动为我们创建这一行对应的内容。yarn add -D webpack-dev-server
。node_modules/.bin/webpack-dev-server
,可以进入 webpack 的开发者模式。在 package.json 中添加:
{
...
"scripts": {
"build": "webpack",
"start": "node_modules/.bin/webpack-dev-server"
}
...
}
在项目根目录的命令行中可以使用 yarn build 代替 webpack 进行编译;可以使用 yarn start 代替 node_modules/.bin/webpack-dev-server 进入开发者模式。
yarn add -D typescript ts-loader
安装必要的包。// tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
// 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/
}
]
}
};