0
点赞
收藏
分享

微信扫一扫

webpack打包优化

史值拥 2022-05-06 阅读 58

1. 配置打包分析工具

# NPM 
npm install --save-dev webpack-bundle-analyzer
# Yarn 
yarn add -D webpack-bundle-analyzer
  • 配置配置文件
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}

具体配置项可见文档 https://www.npmjs.com/package/webpack-bundle-analyzer

  • 修改启动命令
npm run serve --report
npm run build --report

2.配置Webpack的externals

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
  configureWebpack: {
    plugins: [
      new BundleAnalyzerPlugin()
    ],
    publicPath: "./",
  },
  configureWebpack: (config) => {
    config.externals = {
      vue: "Vue",
      vuex: "Vuex",
      "vue-router": "VueRouter",
      'element-ui': "ELEMENT",
      axios: "axios",
    };
  },
};
  • 引入cdn
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vuex/3.6.2/vuex.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.5.3/vue-router.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.6/index.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.min.js"></script>
<link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.6/theme-chalk/index.min.css" rel="stylesheet">

打包验证

运行npm run dist --report

  • 本地测试dist包

步骤:

  1. 创建prorun(一个文件夹)目录
  2. 把dist打包文件复制给prorun目录
  3. 给prorun目录下新建 package.json文件(也可运行npm init自动生成,生成的package.json就不用手动配置了)
  4. 配置package.json
{
  "name": "prorun",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  }
}
  1. 运行npm i express安装express
  2. 新建app.js,并配置如下代码
// 通过express创建一个http服务
// 引入express
var express = require('express')

// 创建express实例化对象
var app = express()

// 设置dist目录被托管(运行内部的文件)
app.use(express.static('./dist'))

// 创建http服务
app.listen(8888,function(){
  console.log('项目已经运行,具体在\n\nhttp://127.0.0.1:8888')
})
  1. 执行node app.js
举报

相关推荐

0 条评论