webpack5项目之基本配置详解
作者:yaoyongcsdn
本文介绍了如何配置webpack项目,包括设置项目出入口、模式、devtool、本地环境和内存HTML插件,以及安装开发工具webpack-dev-server
一.配置项目出入口
webpack.config.js(文档)
const path = require('path');
module.exports = {
entry: {
//设置入口文件为src/main.js 将来会被打包到dist目录下
main: './src/main.js',
//other: './src/other.js',//多入口文件,打包后会在dist目录下生成相应js
},
output: {
//打包后文件名
filename: '[name]-[contenthash:6].js',
//指定打包文件输出目录
path: path.resolve(__dirname, 'dist'),
//在每次构建前清理 /dist 文件夹
clean: true,
},
};二.添加模式
webpack.config.js(文档)
const path = require('path');
module.exports = {
mode: 'development',
entry: {
//设置入口文件为src/main.js 将来会被打包到dist目录下
main: './src/main.js',
//other: './src/other.js',//多入口文件,打包后会在dist目录下生成相应js
},
output: {
//打包后文件名
filename: '[name]-[contenthash:6].js',
//指定打包文件输出目录
path: path.resolve(__dirname, 'dist'),
//在每次构建前清理 /dist 文件夹
clean: true,
},
};如果没有设置,webpack 会给 mode 的默认值设置为 production
三.添加devtool
webpack.config.js(文档)
const path = require('path');
module.exports = {
mode: 'development',
//将编译后的代码映射回原始源代码
devtool: 'inline-source-map',
entry: {
//设置入口文件为src/main.js 将来会被打包到dist目录下
main: './src/main.js',
//other: './src/other.js',//多入口文件,打包后会在dist目录下生成相应js
},
output: {
//打包后文件名
filename: '[name]-[contenthash:6].js',
//指定打包文件输出目录
path: path.resolve(__dirname, 'dist'),
//在每次构建前清理 /dist 文件夹
clean: true,
},
};四.安装本地环境和内存html插件
npm install -D webpack webpack-cli html-webpack-plugin
webpack.config.js(文档)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
devtool: 'inline-source-map', //将编译后的代码映射回原始源代码
entry: './src/main.js',
output: {
filename: '[name]-[contenthash:6].js',//打包后文件名
path: path.resolve(__dirname, 'dist'),
clean: true, //在每次构建前清理 /dist 文件夹
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html', //打包的html模板文件
title: 'webpack-demo',
filename: "index.html", //打包后的html名称
}),
],
};五.安装开发工具
安装开发工具webpack-dev-server(此处安装3.11.2版本,最新版本4.0.0有兼容性问题)
npm install -D webpack-dev-server@3.11.2
在package.json中添加执行脚本
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack serve --open --port 3000",
"build": "webpack"
},package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack serve --open --port 3000",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^5.3.2",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^3.11.2"
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
