webpack 基础搭建
从头搭建一个webpack项目,一定要有清晰的思路去做这件事情。虽然配置众多,只要掌握好思路就会从容不迫。
新建目录
mkdir webpack-project
创建package.json
cd webpack-project
npm init
首先要安装的是webpack相关依赖:
npm i -D webpack webpack-cli webpack-dev-server
为了兼容ES6,ES7,ES8等更高级的语法,我们需要babel相关插件来将高级语法转换成ES5的语言:
npm i -D babel-loader@7 babel-core babel-preset-env babel-plugin-transform-runtime babel-plugin-transform-decorators babel-plugin-transform-decorators-legacy
npm i -D node-sass scss-loader css-loader style-loader
npm i -D html-webpack-plugin
在写配置文件之前,新建src
目录。确定HTML文件位置和入口JS目录位置。并新建webpack.config.js
文件:
├── node_modules
├── webpack.config.js
├── src
│ ├── index.html
│ └── js
│ └── index.js
└── package.json
webpack.config.js
文件导出的是一个配置对象,对象常用的有以下几个部分:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path')
module.exports = {
mode: 'development', // dev(不带注释等) prod
entry: {
index: path.resolve(__dirname, './src/js/index.js'),
// list: path.resolve(__dirname, './src/js/list.js') // 多页面开发
},
output: {
path: path.resolve(__dirname + '/dist'), // 打包到哪一个文件夹下
filename: 'js/[name].js', // name是规则
},
module: {
// 创建模块时,匹配请求的规则数组。这些规则能够修改模块的创建方式。 这些规则能够对模块(module)应用 loader,或者修改解析器(parser)。
rules: [{
// 模块打包规则
test: /\.js$/, // 匹配文件后缀名
loader: 'babel-loader',
exclude: path.resolve(__dirname, 'node_modules'),
}, {
test: /\.css$/,
use: ['style-loader','css-loader'] // 从右到左倒着处理,先处理css-loader,再处理style-loader
}, {
test: /\.scss$/,
use: ['style-loader','css-loader', 'scss-loader']
}]
},
plugins: [ // 里面都是实例化对象
new HtmlWebpackPlugin({
// 每个插件基本都是一个构造函数
filename: 'index.html',
template: path.resolve(__dirname, './src/index.html'),
chunks: ['index'],
excludeChunks: ['node_modules']
})
],
devServer: {
// 开发服务器
open: true, // 启动项目后,自动打开浏览器
host: 'localhost',
port: 8014
}
}
在package.json
中配置启动和打包命令:scripts
部分
{
"name": "webpack-learning",
"version": "1.0.0",
"description": "webpack start",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js",
"webpack": "webpack --config webpack.config.js",
"start": "npm run dev",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"webpack"
],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-decorators": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"css-loader": "^5.1.1",
"html-webpack-plugin": "^5.2.0",
"node-sass": "^5.0.0",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.24.3",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.2"
}
}
启动:
npm start
若有报错:Error: Cannot find module 'webpack-cli/bin/config-yargs'
,则将webpack-cli4(默认安装) 要换成webpack-cli@3依赖包
npm uninstall webpack-cli
npm i -D webpack-cli@3
再启动,应该能正常启动。
webpack中所需的依赖包很多,掌握了清晰的基础思路,则不会丢包导致启动报错的情况。之后还会继续研究下webpack的打包原理。