webpack4 配置 vue项目

成套的选用插件.

包括文档.本地数据模拟服务.项目生产.项目测试.

{
  "name": "vue",
  "version": "1.0.0",
  "main": "index.js",
  "private": true,
  "scripts": {
    "dev": "webpack-dev-server -d  --env.NODE_ENV=development",
    "start": "node ./Server/bin/www",
    "doc": "gitbook build ./ ./Server/public/doc/",
    "prod": "webpack -p --env.NODE_ENV=production"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "element-ui": "^2.4.7",
    "vue": "^2.5.17",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.1",
    "babel-plugin-component": "^1.1.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-3": "^6.24.1",
    "body-parser": "~1.18.2",
    "clean-webpack-plugin": "^0.1.19",
    "cookie-parser": "~1.4.3",
    "css-loader": "^1.0.0",
    "debug": "~2.6.9",
    "ejs": "~2.5.7",
    "eslint": "^5.6.0",
    "eslint-loader": "^2.1.0",
    "eslint-plugin-html": "^4.0.5",
    "eslint-plugin-vuefix": "^0.2.1",
    "exports-loader": "^0.7.0",
    "express": "~4.15.5",
    "file-loader": "^2.0.0",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.8.1",
    "less-loader": "^4.1.0",
    "mini-css-extract-plugin": "^0.4.3",
    "morgan": "~1.9.0",
    "optimize-css-assets-webpack-plugin": "^5.0.1",
    "script-loader": "^0.7.2",
    "style-loader": "^0.23.0",
    "serve-favicon": "^2.5.0",
    "uglifyjs-webpack-plugin": "^2.0.1",
    "url-loader": "^1.1.1",
    "vue-loader": "^15.4.2",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.5.17",
    "webpack": "^4.19.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.8",
    "webpack-merge": "^4.1.4",
    "gitbook-plugin-collapsible-menu": "^1.0.3",
    "gitbook-plugin-mermaid-gb3": "2.1.0",
    "gitbook-plugin-splitter": "0.0.8",
    "gitbook-plugin-theme-vuejs-2": "1.0.0"
  }
}
复制代码

由单一入口多分支来控制在不同环境中工具使用情况,使用env 中添加参数实现.

webpack.config.js

const VueLoaderPlugin = require('vue-loader/lib/plugin')
const merge = require('webpack-merge');
const path = require('path');
//引入html模板插件
const HtmlWebpackPlugin = require('html-webpack-plugin');
//打包到 配置项中 文件夹
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

/* 自动获取项目名 */
const filepath = path.resolve(__dirname, './Server/public/prod');
module.exports = env => {
  let publicPath = '/';
  let run = {};
  if (env.NODE_ENV == 'production') {
    publicPath = './';
    console.log('启动-->生产模式\n');
    console.log('prod完成后的文件放在---->' + filepath + "\n\n");
    run = require('./webpack/webpack.prod'); //引入不同环境下的配置
  } else if (env.NODE_ENV == 'development') {
    console.log('启动-->本地开发模式\n');
    run = require('./webpack/webpack.dev'); //引入不同环境下的配置
  }
  return merge({
    //输入文件路径, 可指定为多个.
    entry: {
      main: ['babel-polyfill', './index.js'],
    },
    /**
     输出文件路径, 当输入 为多个时,指定固定名字.会创建同名文件,新的文件会覆盖旧的.
     最后只有剩下一个文件.html模板引入时只能找到一个;
     */
    output: {
      path: filepath,
      chunkFilename: 'js/[name].js', //当使用动态加载的模块,使模块另外打包;
      filename: 'js/[name].js',
      publicPath: publicPath //动态路径.把产品里的 URL SRC 中的连接设置成以'/'为根目录绝对地址.
    },
    //加载器  模块  配置 对象
    module: {
      // 文件加载 规则,检查以test属性值为后缀名的文件时,对应使用的加载器;
      rules: [{
          test: /\.(css|less)$/, //用正则验证文件后缀名,
          use: [
            env.NODE_ENV !== 'production' ? 'vue-style-loader' : MiniCssExtractPlugin.loader,
            'css-loader',
            'less-loader'
          ]
        },
        {
          test: /\.vue$/,
          loader: 'vue-loader',
        },
        {
          test: /\.(jpg|png|gif)$/,
          use: [{
            loader: 'url-loader',
            options: {
              limit: 8192,
              publicPath: "../", //文件根路径需要配置,会有生成路径问题
              mimetype: 'image/png',
              name: 'images/[name].[ext]',
              fallback: 'file-loader'
            }
          }],
        },
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: "babel-loader"
        },
        //加载字体.
        {
          test: /\.(woff|woff2|eot|ttf|otf)$/,
          loader: 'url-loader',
          options: {
            name: 'font/[name].[ext]',
            fallback: 'file-loader'
          }
        }, {
          enforce: "pre",
          test: /\.js$/,
          exclude: /node_modules/,
          loader: "eslint-loader",
          options: {
            /**
             *开启 eslint  自动修复功能 .
             * --------注意---------> 可能造成无限构建循环.
             * 造成问题时可关闭此项
             */
            // fix: true,
            cache: true //缓存检查结果 ,加快构建速度
          }
        }
      ]
    },
    plugins: [
      //html模板实例化+配置
      new HtmlWebpackPlugin({
        filename: 'index.html',
        template: './public/index.html',
        inject: true,
        favicon: './public/favicon.ico'
      }),
      new VueLoaderPlugin()
    ]
  }, run)
}
复制代码

不同环境下两个配置文件.

打包配置 prod.

const path = require('path');
const webpack = require('webpack');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  mode: 'production',
  optimization: {
    minimizer: [new UglifyJsPlugin({
        test: /\.js(\?.*)?$/i,
        parallel: true,
        sourceMap: true,
        uglifyOptions: {
          compress: {
            // 在UglifyJs删除没有用到的代码时不输出警告
            warnings: false,
            // 删除所有的 `console` 语句,可以兼容ie浏览器
            drop_console: true,
            // 内嵌定义了但是只用到一次的变量
            collapse_vars: true,
            // 提取出出现多次但是没有定义成变量去引用的静态值
            reduce_vars: true,
          },
          output: {
            // 最紧凑的输出
            beautify: false,
            // 删除所有的注释
            comments: false,
          },
          mangle: true, // Note `mangle.properties` is `false` by default.
        }
      }),
      // 压缩CSS
      new OptimizeCSSPlugin({
        assetNameRegExp: /\.optimize\.css$/g,
        cssProcessor: require('cssnano'),
        cssProcessorPluginOptions: {
          preset: ['default', {
            discardComments: {
              removeAll: true
            }
          }],
        },
        canPrint: false
      }),
    ],
    splitChunks: {
      cacheGroups: {
        commons: { // 抽离自己写的公共代码
          chunks: "initial",
          name: "common", // 打包后的文件名,任意命名
          minChunks: 2, //最小引用2次
        },
        vendor: { // 抽离第三方插件
          test: /node_modules/, // 指定是node_modules下的第三方包
          chunks: 'initial',
          name: 'vendor', // 打包后的文件名,任意命名
          // 设置优先级,防止和自定义的公共代码提取时被覆盖,不进行打包
          priority: 10
        },
      }
    },
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.min.js'
    }
  },
  plugins: [
    //先清理文件夹
    new CleanWebpackPlugin(['prod'], {
      root: path.resolve(__dirname, '../Server/public/')
    }),
    //打包css
    new MiniCssExtractPlugin({
      filename: "css/[name].css"
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: "production"
      }
    })
  ]
};
复制代码

引入的文件.开发服务配置

const webpack = require('webpack');

module.exports = {
  mode: 'development',
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.js'
    }
  },
  devtool: 'cheap-module-eval-source-map',
  devServer: {
    inline: true, //自动刷新页面
    // open: true, //自动打开浏览器
    quiet: false, //控制台中不输出打包的信息
    //设置 在局域网中广播  localhost:9091
    host: "0.0.0.0",
    noInfo: true,
    port: 9091, //监听端口
    //如果要开 启 webpack-dev-sever 上的热更新,必须加上这个选项.但是一般都不能自动刷新浏览器
    hot: true,
    //当出现编译器错误或警告时,在浏览器中显示全屏叠加
    overlay: {
      errors: true
    },
    //请求地址代理地址
    proxy: {
      '/': {
        target: 'http://localhost:7070/',
        //pathRewrite: {"^/anyway/" : ""},
        // changeOrigin: true,
        secure: false
      }
    }
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ]
};
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值