webpack配置学习

1,npm init -y 初始化项目,项目会多出一个package.json文件

2,npm install webpack webpack-cli -D 项目会多出一个node_modules文件

3,在项目中创建一个webpack.config.js文件

const path=require('path')

module.exports={
	mode:'development',//开发模式,文件没有压缩,如果是生产项目,文件就会压缩,用production
	entry:path.join(__dirname,'src','index.js'),
	output:{
		filename:'bundle.js',
		path:path.join(__dirname,'dist')
	}
}

在package.json中添加

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },

运行npm run build,项目就会打包

以上是只有js,下面是有添加html的,

1,解析html的插件,npm install html-webpack-plugin

2,启动服务的插件,npm install webpack-dev-server

3,在webpack.config.js中进行插件配置

const path=require('path')
const HtmlWebpackPlugin=require('html-webpack-plugin')

module.exports={
	mode:'development',
	entry:path.join(__dirname,'src','index.js'),
	output:{
		filename:'bundle.js',
		path:path.join(__dirname,'dist')
	},
	plugins:[
		new HtmlWebpackPlugin({
			template:path.join(__dirname,'src','index.html'),
			filename:'index.html'
		})
	],
	devServer:{
		port:3000,
		contentBase:path.join(__dirname,'dist')
	}
}

4,在package.json中添加

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "dev":"webpack-dev-server"
  },

5,运行npm run dev,然后在网页输入localhost:3000就可以访问

babel配置

1,npm install @babel/core @babel/preset-env babel-loader -D    //core是核心,prese-env配置,babel-loader给webpack用的插件,

2,创建一个.babelrc文件,

{
	"presets":["@babel/preset-env"]
}

3,在webpack.config.js中进行配置

module:{
		rules:{
			test:/\.js$/,
			loader:['babel-loader'],
			include:path.join(__dirname,'src')
		}
	}

配置生产环境的webpack

1,创建一个webpack.prod.js文件

const path=require('path')
const HtmlWebpackPlugin=require('html-webpack-plugin')

module.exports={
	mode:'production',
	entry:path.join(__dirname,'src','index.js'),
	output:{
		filename:'bundle.[contenthash].js',
		path:path.join(__dirname,'dist')
	},
	module:{
		rules:{
			test:/\.js$/,
			loader:['babel-loader'],
			include:path.join(__dirname,'src')
		}
	}
	plugins:[
		new HtmlWebpackPlugin({
			template:path.join(__dirname,'src','index.html'),
			filename:'index.html'
		})
	]
}

2,更改package.json文件

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.prod.js",
    "dev": "webpack-dev-server"
  },

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值