webpack4搭建vue环境

本文详细介绍了Webpack的基础配置,包括入口、出口、HTML模板处理、样式资源管理和不同环境的配置。同时,深入探讨了性能优化策略,如代码压缩、CSS抽离、HMR、oneOf、缓存利用、tree shaking、代码分割和chunkhash等。通过实例展示了如何实现这些优化,以提升项目的构建速度和运行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、config/webpack.base.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const NODE_ENV = process.env.NODE_ENV;
console.log(NODE_ENV);

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.vue$/i,
        loader: 'vue-loader',
        options: {
          css: [
            NODE_ENV === 'production' ? MiniCssExtractPlugin.loader : 'vue-style-loader',
            'css-loader',
            'postcss-loader',
            'sass-loader'
          ]
        },
        include: /src/
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          'thread-loader',
          'babel-loader?cacheDirectory'
        ],
        include: /src/
      },
      {
        test: /\.css$/i,
        use: [NODE_ENV === 'production' ? MiniCssExtractPlugin.loader : 'style-loader', 'css-loader', 'postcss-loader'],
        include: /src/
      },
      {
        test: /\.less$/i,
        use: [NODE_ENV === 'production' ? MiniCssExtractPlugin.loader : 'style-loader', 'css-loader', 'postcss-loader', 'less-loader'],
        include: /src/
      },
      {
        test: /\.s[ac]ss$/i,
        use: [NODE_ENV === 'production' ? MiniCssExtractPlugin.loader : 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
        include: /src/
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              // 小于8k转为base64格式,大于8k用file-loader处理
              limit: 8192,
              name: 'assets/images/[name]_[hash:6].[ext]'
            },
          },
        ],
        include: /src/
      },
      {
        test: /\.html$/i,
        loader: 'html-loader',
        include: /src/
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'assets/media/[name]_[hash:6].[ext]'
            }
          },
        ],
        include: /src/
      }
    ],
  },
  resolve: {
    extensions: ['.vue', '.js', '.json', '.css', 'less', 'scss'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  plugins: [
    new VueLoaderPlugin(),
    // 应用HTML模板
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
}
2、config/webpack.dev.config.js
const path = require('path');
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.base.config');

function resolve(p) {
  return path.resolve(__dirname, p);
}
module.exports = merge(commonConfig, {
  mode: 'development',
  output: {
    path: resolve('../dist'),
    filename: 'js/build.js'
  },
  devServer: {
    // 资源路径
    contentBase: resolve('../dist'),
    // 启动gzip压缩
    compress: true,
    hot: true,
    open: false,
    port: 9000,
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: { '^/api': '' }
      },
    },
  }
});
3、config/webpack.prod.config.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.base.config');

function resolve(p) {
  return path.resolve(__dirname, p);
}

module.exports = merge(commonConfig, {
  mode: 'production',
  output: {
    path: resolve('../dist'),
    filename: 'js/[name].[chunkhash:6].js'
  },
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        parallel: true,
      }),
      new TerserPlugin({
        cache: true,
        parallel: true
      })
    ],
    /* 
    抽离公共代码、第三方库
    自动分析多入口chunk中有没有公共的文件。如果有会打包成单独的chunk,避免重复打包多次
    */
    runtimeChunk: {
      name: (entrypoint) => `runtime~${entrypoint.name}`,
    },
    splitChunks: {
      chunks: "all"
    }
  },
  plugins: [
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash:6].css',
      chunkFilename: 'css/[id].[contenthash:6].css'
    })
  ]
})
4、.babelrc
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "corejs": {
          "version": 3
        },
        "targets": {
          "chrome": "40",
          "firefox": "40",
          "ie": "9",
          "safari": "10",
          "edge": "15"
        }
      }
    ]
  ],
  "plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-syntax-dynamic-import"
  ]
}
5、postcss.config.js
module.exports = {
  plugins: [
    [
      "postcss-preset-env"
    ]
  ]
}
6、package.json
{
  "name": "webpack-study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config ./config/webpack.dev.config.js",
    "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.prod.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.10",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.13.10",
    "@babel/preset-env": "^7.13.12",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^3.0.0",
    "core-js": "^3.9.1",
    "cross-env": "^7.0.3",
    "css-loader": "^5.1.3",
    "css-minimizer-webpack-plugin": "^1.3.0",
    "express": "^4.17.1",
    "file-loader": "^6.2.0",
    "html-loader": "^1.3.2",
    "html-webpack-plugin": "^4.5.2",
    "less": "^4.1.1",
    "less-loader": "^7.3.0",
    "mini-css-extract-plugin": "^1.3.9",
    "postcss-loader": "^4.2.0",
    "postcss-preset-env": "^6.7.0",
    "sass": "^1.32.8",
    "sass-loader": "^10.1.1",
    "style-loader": "^2.0.0",
    "terser-webpack-plugin": "^4.2.3",
    "thread-loader": "^3.0.1",
    "url-loader": "^4.1.1",
    "vue-loader": "^15.9.6",
    "vue-style-loader": "^4.1.3",
    "vue-template-compiler": "^2.6.12",
    "webpack": "^4.46.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.7.3"
  },
  "dependencies": {
    "@babel/runtime": "^7.13.10",
    "vue": "^2.6.12",
    "vue-router": "^3.5.1"
  },
  "browserslist": {
    "development": [
      "last 4 chrome version",
      "last 4 firefox version",
      "last 4 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  }
}

7、性能优化部分
# webpack4学习笔记
## 一、项目基础文件
--  src、config、public文件夹,index.html、index.js
## 二、配置webpack.config.js
--  1.装包
    npm i webpack webpack-cli -D
--  2.配置入口和出口
--  3.应用HTML模板
    npm install html-webpack-plugin -D
--  4.修改npm启动命令
--  5、处理样式资源

## 性能优化
### 1CSSJS代码压缩
### 2CSS抽离成单独文件,按需加载
### 3HMR,只重新加载已改变的文件
### 4、oneOf,每个文件loader只处理一次
### 5、babel缓存,提高打包速度。
### 6JS文件设置chunkhash,CSS文件contenthash,设置缓存,hash值不变,直接取缓存文件渲染
### 7、tree shaking,去掉没有用到的代码
    前提:1、必须使用ES6模块化。2、开启production环境
    只要是模块化,打包后会自动去掉无用代码
### 8、代码分割---splitChunks
    抽离公共代码、第三方库
    自动分析多入口chunk中有没有公共的文件。如果有会打包成单独的chunk,避免重复打包多次
    ES10import('url')动态导入语法可将文件单独打包成一个chunk,类似vue的路由懒加载语法
    splitChunks: {
        chunks: "all"
    }
    这样会有个问题,main.js中记录其他文件的hash值,如果其他文件变了,main.js也会重新打包
    runtimeChunk为每个只含有 runtime 的入口添加一个额外 chunk
    runtimeChunk: {
      name: (entrypoint) => `runtime~${entrypoint.name}`,
    }

--  hash:每次webpack构建时会生成一个唯一的hash值。一个文件改变,所有的hash值都会变
    chunkhash:根据chunk生成的hash值。如果JSCSS都用chunkhash,因为JSCSS属于同一个chunk,因此hash值一样,某一个文件改变时,同一个chunk的JSCSS都会重新打包
    contenthash:根据文件的内容生成hash值。不同文件hash值一定不一样
    优化:JS文件用chunkhash,CSS文件用contenthash
--  多进程打包 thread-loader


好的,我可以为您提供有关如何使用Webpack 4来构建Vue项目的步骤: 1. 创建项目文件夹并初始化npm(如果您尚未完成): ``` mkdir your-project-name cd your-project-name npm init -y ``` 2.\u4e3a\u9879\u76ee\u6dfb\u52a0Webpack 4\uff0c\u60a8\u53ef\u4ee5\u9047\u5230\u4ee5\u4e0b\u6b65\u9aa41\u3002\u5728\u9879\u76ee\u7684\u6839\u76ee\u5f55\u4e2d\u521b\u5efa\u4e00\u4e2a\u65b0\u6587\u4ef6\u5939\u4ee5\u7ed3\u6784\u4e00\u4e2a\u7f16\u7801\u6587\u4ef6\u5e76\u5c06\u5b83\u5f00\u59cb\u8bbe\u7f6e\u4e3awebpack\u3002 ``` mkdir src touch src/index.js ``` 3. \u5728\u9879\u76ee\u5e93\u4e2d\u5b89\u88c5Webpack 4\uff0c\u4f7f\u7528npm\u5b89\u88c5webpack\u548cwebpack-cli\u3002 ``` npm install webpack webpack-cli --save-dev ``` 4. \u5728\u9879\u76ee\u5e93\u6839\u76ee\u5f55\u4e2d\u6dfb\u52a0\u4e00\u4e2awebpack.config.js\u6587\u4ef6\uff0c\u5e76\u914d\u7f6eWebpack\u7684\u914d\u7f6e\u9879\u3002 ``` touch webpack.config.js ``` 5. \u7f16\u8f91webpack.config.js\u6587\u4ef6\uff0c\u914d\u7f6e\u9879\u76ee\u7684\u8f93\u51fa\u6587\u4ef6\u540d\u79f0\u548c\u8f93\u51fa\u76ee\u5f55\u3002 ``` const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, }; ``` 6. \u7f16\u8f91src/index.js\u6587\u4ef6\uff0c\u4e3aVue\u6a21\u5757\u6dfb\u52a0\u4ee5\u53ca\u8fd0\u884c\u4e3aVue\u6a21\u5757\u7684\u5e93\u3002\u5728\u6b64\u4f7f\u7528npm\u5b89\u88c5Vue\u3002 ``` npm install vue --save ``` 7. \u7f16\u8f91src/index.js\u6587\u4ef6\uff0c\u5e76\u5b9e\u73b0\u5728\u9879\u76ee\u4e2d\u4f7f\u7528Vue\u6a21\u5757\u3002 ``` import Vue from 'vue'; new Vue({ el: '#app', template: '<div>Hello, Vue!</div>', }); ``` 8. \u521b\u5efa\u9879\u76ee\u7684index.html\u6587\u4ef6\uff0c\u4e3a好的,让我来简单介绍一下如何使用Webpack 4来构建Vue项目: 1. 安装Node.js和npm 确保你的电脑上已经安装了Node.js和npm。你可以通过访问Node.js官方网站 (https://nodejs.org/) 下载并安装。 2. 创建项目文件夹 在命令行中创建一个新的项目文件夹,例如: ``` mkdir my-vue-project ``` 3. 初始化npm 进入该项目文件夹,并在命令行中输入以下命令来初始化npm: ``` cd my-vue-project npm init -y ``` 4. 安装Vue.js 使用npm安装Vue.js和Vue Loader: ``` npm install vue vue-loader vue-template-compiler --save-dev ``` 5. 安装Webpack 4及其相关插件 使用npm安装Webpack 4及其相关插件: ``` npm install webpack webpack-cli webpack-dev-server html-webpack-plugin --save-dev ``` 6. 创建Webpack配置文件 在项目根目录下创建一个webpack.config.js文件,并在其中添加以下内容: ``` const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], }, }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', }), ], devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, port: 9000, }, }; ``` 7. 创建项目文件夹结构 在项目根目录下创建一个src文件夹,并在其中创建一个main.js文件和一个index.html文件。在src文件夹中再创建一个components文件夹,并在其中创建一个HelloWorld.vue组件文件。具体的文件夹结构如下: ``` my-vue-project/ src/ components/ HelloWorld.vue main.js index.html webpack.config.js package.json ``` 8. 编写Vue组件 打开HelloWorld.vue文件,并添加以下代码: ```html <template> <div> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'HelloWorld', data() { return { msg: 'Welcome to my Vue.js app!', }; }, }; </script> ``` 9. 编写入口文件 打开main.js文件,并添加以下代码: ```javascript import Vue from 'vue'; import HelloWorld from './components/HelloWorld.vue'; new Vue({ el: '#app', components: { HelloWorld, }, template: '<HelloWorld/>', }); ``` 10. 编写HTML文件 打开index.html文件,并添加以下代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>My Vue.js好的,以下是使用webpack4搭建Vue项目的基本步骤: 1. 创建项目文件夹,并初始化为npm项目 ``` mkdir my-project cd my-project npm init -y ``` 2. 安装必要的依赖包 ``` npm install webpack webpack-cli vue vue-loader vue-template-compiler css-loader style-loader --save-dev ``` 3. 在项目根目录下创建webpack配置文件webpack.config.js ``` const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, module: { rules: [ { test: /\.vue$/, use: 'vue-loader' }, { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, plugins: [ new VueLoaderPlugin() ] }; ``` 4. 在src文件夹下创建一个主入口文件main.js和App.vue组件 ``` // main.js import Vue from 'vue'; import App from './App.vue'; new Vue({ el: '#app', render: h => h(App) }); // App.vue <template> <div> <h1>Hello Vue!</h1> </div> </template> <script> export default { name: 'App' }; </script> <style> h1 { color: red; } </style> ``` 5. 在index.html中创建一个div容器,并引入打包后的bundle.js文件 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue Project</title> </head> <body> <div id="app"></div> <script src="./dist/bundle.js"></script> </body> </html> ``` 6. 在package.json中添加启动脚本,方便快速启动项目 ``` "scripts": { "start": "webpack --mode development --watch" }, ``` 7. 在命令行中输入npm start,即可启动项目。在浏览器中打开index.html,即可看到Vue应用程序运行的效果。 希望这个回答能对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值