使用webpack5从0搭建。 webpack配置分为三个文件webpack.dev.js webpack.common.js webpack.pro.js webpack.dev.js 开发环境配置 webpack.common.js 是公共配置文件 webpack.pro.js 生产环境配置 package.json 配置三个命令 serve 启动 对应配置webpack.dev.js build打包 对应配置webpack.pro.js 要求配置babel,eslint,dev-server, css-loader,scss-loader,post-loader,style-loader,css压缩,JS压缩,file-loader url-loader,clean-webpack-plugin, js多进程打包,
时间: 2023-08-16 18:29:45 浏览: 166
好的,您的问题是如何使用webpack5从0搭建项目并配置开发环境和生产环境?
首先,需要安装webpack和webpack-cli:
```
npm install webpack webpack-cli --save-dev
```
然后,我们需要创建三个配置文件:webpack.common.js、webpack.dev.js和webpack.prod.js。
在webpack.common.js中,我们将配置所有环境都需要的共同的部分。例如,我们可以配置entry、output、module和plugins等。示例代码如下:
```javascript
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'],
},
{
test: /\.(sa|sc|c)ss$/,
use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
test: /\.(png|svg|jpg|gif|ico)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: '[name].[contenthash:8].[ext]',
outputPath: 'assets/images',
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[contenthash:8].[ext]',
outputPath: 'assets/fonts',
},
},
],
},
],
},
plugins: [new CleanWebpackPlugin()],
};
```
在webpack.dev.js中,我们将配置开发环境所需要的部分。例如,我们可以配置devServer、devtool等。示例代码如下:
```javascript
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common');
module.exports = merge(commonConfig, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
port: 8080,
hot: true,
open: true,
},
optimization: {
minimize: false,
},
});
```
在webpack.prod.js中,我们将配置生产环境所需要的部分。例如,我们可以配置optimization、devtool等。示例代码如下:
```javascript
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = merge(commonConfig, {
mode: 'production',
devtool: 'source-map',
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
});
```
最后,在package.json中配置三个命令:
```json
{
"scripts": {
"serve": "webpack serve --config webpack.dev.js",
"build": "webpack --config webpack.prod.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
}
```
以上是一个基本的webpack5项目的配置过程,其中包含了babel、eslint、dev-server、css-loader、scss-loader、post-loader、style-loader、css压缩,JS压缩,file-loader、url-loader、clean-webpack-plugin、js多进程打包等常用配置。
阅读全文