我们本次实践的目标是:
使用webpack搭建一个前端自动化工程项目
项目的功能需要具有以下几个功能
1.自动打包
2.自动压缩
3.热更新
4.scss转css
5.es6转es5
目录结构:
-demo
-dist
-build
-webpack.base.config.js
-webpack.dev.config.js
-webpack.prod.config.js
-src
-html
-js
-css
-images
-package.json
(使用es6语法,并使用scss来进行预编译)
Begin:
新建文件下,在文件夹下打开终端,初始化项目
npm init
一路回车,完成后文件夹的根目录会生成一个package.json的文件
本地安装webpack(默认已全局安装)
npm i webpack webpack-cli webpack-dev-server webpack-merge
build文件夹内新建如上三个js文件
//安装loader
npm i node-sass sass-loader css-loader babel-loader url-loader
//安装html模板插件 和 分离压缩css插件
npm i mini-css-extract-plugin html-webpack-plugin
webpack.base.config.js
const MiniCssPlugin = require('mini-css-extract-plugin');
const htmlPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
//入口
entry: {
index: path.resolve(__dirname, '../src/js/entry.js')
},
output: {
publicPath: '',
path: path.resolve(__dirname, '../dist'),
filename: 'js/[name].[hash:8].js'
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/i,
use: [
// Creates `style` nodes from JS strings
{
loader: MiniCssPlugin.loader,
options: {
publicPath: '/'
}
},
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
//处理静态文件
{
test: /\.(jpeg|jpg|png|gif|woff|ttf)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
name: 'images/[name].[ext]',
},
},
],
},
]
},
plugins: [
new htmlPlugin({
template: path.resolve(__dirname, '../src/html/index.html'),
}),
new MiniCssPlugin({
filename: 'css/[name].[hash:8].css',
chunkFilename: 'css/index.[hash:8].css'
})
]
}
webpack.dev.config.js
const config = require('./webpack.base.config.js');
const merge = require('webpack-merge');
const webpack = require('webpack');
module.exports = merge(config, {
mode: 'development',
devtool: "#@inline-source-map",
devServer: {
port: '6688',
contentBase: '../dist',
hot: true,
compress: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
]
})
webpack.prod.config.js
const config = require('./webpack.base.config');
const merge = require('webpack-merge');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = merge(config, {
mode: 'production',
plugins: [
new CleanWebpackPlugin()
]
})
以上文件配置好之后,在对应文件夹新建对应名称的文件,然后打开根目录下的package.json文件,在scripts下配置两个属性
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --config build/webpack.dev.config.js",
"build": "webpack --open --config build/webpack.prod.config.js"
},
//启动项目
npm run dev
//打包项目
npm run build