webpack是如何打包的,怎么配置?loader的使用
webpack的安装
全局安装
1
| npm i webpack webpack-cli -g
|
项目安装
1
| npm i webpack webpack-cli -D
|
项目初始化
项目中的webpack执行打包(npx)
es6 导入导出规范
1 2
| let wang = require('./wang.js') export default {}
|
commonJS(cmd)导入导出规范
1 2
| import wang from './wang.js' module.exports = {}
|
四个核心概念:
- 入口(entry):程序的入口 就是你想要打包的目录
- 输出(output):打包后的文件位置
- loader:对于你想要打包的文件进行转换的配置
- 插件(plugins):解决loader无法实现的事情
新建文件webpack.config.js
1 2 3 4 5 6 7 8 9 10
| const path = require('path');
module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' } mode: 'production' };
|
__dirname 当前路径
path.resolve(__dirname, ‘dist’) 解析当前路径的绝对路径
path.join(__dirname, ‘dist’) 拼接当前路径的绝对路径
指定使用哪个文件进行打包 一个开发模式 一个生产模式
1
| npx webpack --config webpack.custom.config.js
|
快捷命令输出
1 2 3 4 5
| "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build":"webpack --config webpack.custom.config.js" }
|
使用webpack-dev-server(推荐)
会开启服务器
安装
1 2 3
| npm i webpack-dev-server -D
"dev": "webpack-dev-server"
|
自动编译完成时的地址是127.0.0.1:8080/
打包后的文件在内存中
配置dev
1 2 3 4 5 6 7 8 9 10
| const path = require('path'); module.exports = { devServer: { open: true, port: 3000, hot: true, } };
|
html-webpack-plugin插件(把html打包—服务器使用)
1
| npm i html-webpack-plugin -D
|
html-webpack-plugin插件使用
1 2 3 4 5 6 7 8 9 10
| const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { plugins: [ new HtmlWebpackPlugin({ filename: "index.html", template: "./src/index.html" }) ] };
|
会自动引入js文件
loader使用
处理css文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| npm i css-loader style-loader -D
module.exports = { module: { rules: [ { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, ], }, };
|
处理less和sass
1 2 3 4 5
| npm i less less-loader sass-loader node-sass -D
{ test: /\.less$/, use: ['style-loader','css-loader', 'less-loader',], }, {test: /\.s[ac]ss$/i,use: ['style-loader','css-loader', 'sass-loader',],},
|
处理img(图片)和 字体图标
1 2 3 4
| npm i file-loader -D
{test: /\.(png|jpeg|gif|bmp|jpg)$/,use: "file-loader"},
|
处理字体图标
1
| {test: /\.(woff|woff2|eot|svg|ttf)$/,use: "file-loader"},
|
处理图片的其他高级功能(url-loader)
1 2 3 4 5 6 7 8
| npm i url-loader -D
{test: /\.(png|jpeg|gif|bmp|jpg)$/,use: {loader:'url-loader',options:{ limit:5*1024, outputPath:'images', name:'[name]-[hash:8].[ext]', }}},
|
处理babel(兼容js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| npm install babel-loader @babel/core @babel/preset-env webpack -D
{ test: /\.js$/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: ['@babel/plugin-proposal-class-properties'] } exclude: /node_modules/ } }
|
处理generator函数
1 2 3 4
| npm install --save-dev @babel/plugin-transform-runtime npm install --save @babel/runtime
{"plugins": ["@babel/plugin-transform-async-to-generator"]},
|
babelrc
分配好具体的配置在哪