vue项目的webpack4.X配置
这两天摆弄webpack,躺过很多坑,直到今天看了一位博主的文章才得以解决。他对配置中的各个部分做说明。
下面的配置99.9%抄自博主: https://www.cnblogs.com/nianyifenzhizuo/p/10271001.html
安装package.json中的node-sass可能因为网络原因不能成功安装
报错信息有一大串,其中提及python和gyp,其实不用去安装他们。只要执行下面的命令:
npm set sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
npm i node-sass -D
以下为一个vue项目的基本配置:
项目根目录:
{
  "name": "shop",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "clean": "rimraf dist",
    "build": "cross-env NODE_ENV=production webpack --config ./build/webpack.prod.conf.js",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.dev.conf.js",
    "start": "npm run clean && npm run build"
  },
  "author": "asd",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/plugin-transform-runtime": "^7.2.0",
    "autoprefixer": "^9.4.6",
    "babel-loader": "^8.0.5",
    "babel-plugin-transform-remove-console": "^6.9.4",
    "clean-webpack-plugin": "^1.0.1",
    "cross-env": "^5.2.0",
    "css-loader": "^2.1.0",
    "file-loader": "^3.0.1",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.5.0",
    "node-sass": "^4.11.0",
    "optimize-css-assets-webpack-plugin": "^5.0.1",
    "postcss-loader": "^3.0.0",
    "purify-css": "^1.2.5",
    "purifycss-webpack": "^0.7.0",
    "rimraf": "^2.6.3",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "uglifyjs-webpack-plugin": "^2.1.1",
    "url-loader": "^1.1.2",
    "vue-loader": "^15.6.2",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.5.22",
    "webpack": "^4.29.0",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^3.1.14",
    "webpack-merge": "^4.2.1"
  },
  "dependencies": {
    "@babel/preset-env": "^7.3.1",
    "@babel/runtime": "^7.3.1",
    "axios": "^0.18.0",
    "body-parser": "^1.18.3",
    "cookie-parser": "^1.4.4",
    "express": "^4.16.4",
    "glob-all": "^3.1.0",
    "mongoose": "^5.4.11",
    "vue": "^2.5.22",
    "vue-lazyload": "^1.2.6",
    "vue-router": "^3.0.2"
  }
}
package.json
module.exports = {
    loader: 'postcss-loader',
    plugins: [
        require('autoprefixer')
    ]
}
postcss.config.js
{
    "presets": [
        [
            "@babel/preset-env",
            {
                "modules": false
            }
        ]
    ],
    "plugins": [
        "@babel/plugin-transform-runtime", [
            "transform-remove-console",
            {
                "include": ["error", "warn"]
            }
        ]
    ]
}
.babelrc
项目根目录=>build文件夹
const webpack = require('webpack')
const { resolve }= require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const isDev = process.env.NODE_ENV === 'production'
let pluginsConfig = [
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
        title: 'my App',
        template: resolve(__dirname, '../src/index.html')
    }),
    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
        }
    })
]
if (!isDev) {
    pluginsConfig = pluginsConfig.concat(new MiniCssExtractPlugin({
        filename: "css/[name]_[contenthash].css"
    }))
}
module.exports = {
    mode: process.env.NODE_ENV || 'production',
    entry: resolve(__dirname, '../src/index.js'),
    output: {
        filename: 'bundle.js',
        path: resolve(__dirname, '../dist')
    },
    resolve: {
        //引入时可以省略后缀
        extensions: ['.js', '.vue', '.json'],
        alias: {
          'vue$': 'vue/dist/vue.esm.js',
          //@就了代表了src文件夹所在路径
          '@': resolve('src'),
        }
    },
    module: {
        rules: [{
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.scss$/,
                use: [
                    isDev ? 'vue-style-loader' : MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            localIdentName: '[local]_[hash:base64:8]'
                        }
                    },
                    'sass-loader'
                ]
            },
            {
                test: /\.(png|jpg|gif)$/,
                loader: 'url-loader?name=images/[name]-[contenthash:5].[ext]&limit=2000'
            },
            {
                test: /\.js$/,
                loader: 'babel-loader?cacheDirectory',
                exclude: '/node_modules/',
                include: resolve(__dirname, '../src')
            }
        ]
    },
    plugins: pluginsConfig,
}
webpack.base.confg.js
const webpack = require('webpack')
const path = require('path')
const WebPackBaseConfig = require('./webpack.base.conf.js')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const WebPackMerge = require('webpack-merge')
module.exports = WebPackMerge(WebPackBaseConfig, {
    devtool: 'inline-source-map',
    devServer: {
        contentBase: path.join(__dirname, 'dist'), //告诉服务器从哪个目录中提供内容
        compress: true, //启用 gzip 压缩
        port: 9000, //端口号
        host: '0.0.0.0', //默认是 localhost。如果希望服务器外部可访问,则设置为0.0.0.0
        hot: true //启用热替换模块  必须配置 webpack.HotModuleReplacementPlugin
    },
    plugins: [
        new CleanWebpackPlugin(['dist']), //清理文件夹
        new webpack.HotModuleReplacementPlugin(), //启用热替换模块
        new webpack.NamedModulesPlugin() //启用HMR时,插件将显示模块的相对路径
    ]
})
webpack.dev.conf.js
const webpack = require('webpack')
const path = require('path')
const WebPackMerge = require('webpack-merge')
const WebPackBaseConfig = require('./webpack.base.conf.js')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const glob = require('glob-all')
const PurifyCSSPlugin = require('purifycss-webpack')
module.exports = WebPackMerge(WebPackBaseConfig, {
    output: {
        filename: '[name].js',
        chunkFilename: '[name].[chunkhash:5].js',
        path: path.resolve(__dirname, 'dist')
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all'
                }
            }
        },
        runtimeChunk: true,
        minimizer: [
            new UglifyJsPlugin({
                cache: true,
                parallel: true
            }),
            new OptimizeCSSAssetsPlugin()
        ]
    },
    plugins: [
        new PurifyCSSPlugin({
            paths: glob.sync([
                path.join(__dirname, '../src/')
            ]),
            purifyOptions: {
                whitelist: ['*purify*']
            }
        }),
    ]
})
webpack.prod.conf.js
项目根目录=>src文件夹
import Vue from 'vue'
import router from './router/index.js' new Vue({
el: '#app',
router
})
index.js
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<title></title>
</head>
<body>
<div id="app" v-cloak>
<router-view></router-view>
</div>
</body>
</html>
index.html
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view/>
</div>
</template> <script>
export default {
name: 'App'
}
</script> <style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
App.vue
项目根目录=>src文件夹=>router文件夹
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld' Vue.use(Router) export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})
index.js
项目根目录=>src文件夹=>components文件夹
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<ul>
<li>
<a
href="https://vuejs.org"
target="_blank"
>
Core Docs
</a>
</li>
<li>
<a
href="https://forum.vuejs.org"
target="_blank"
>
Forum
</a>
</li>
<li>
<a
href="https://chat.vuejs.org"
target="_blank"
>
Community Chat
</a>
</li>
<li>
<a
href="https://twitter.com/vuejs"
target="_blank"
>
</a>
</li>
<br>
<li>
<a
href="http://vuejs-templates.github.io/webpack/"
target="_blank"
>
Docs for This Template
</a>
</li>
</ul>
<h2>Ecosystem</h2>
<ul>
<li>
<a
href="http://router.vuejs.org/"
target="_blank"
>
vue-router
</a>
</li>
<li>
<a
href="http://vuex.vuejs.org/"
target="_blank"
>
vuex
</a>
</li>
<li>
<a
href="http://vue-loader.vuejs.org/"
target="_blank"
>
vue-loader
</a>
</li>
<li>
<a
href="https://github.com/vuejs/awesome-vue"
target="_blank"
>
awesome-vue
</a>
</li>
</ul>
</div>
</template> <script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script> <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped, lang="sass" src='@/assets/css/admin.scss'></style>
HelloWorld.vue
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
$link-color: #ff6000;
a {
  color: $link_color;
}
admin.scss
vue项目的webpack4.X配置的更多相关文章
- 基于Vue cli生成的Vue项目的webpack4升级
		前面的话 本文将详细介绍从webpack3到webpack4的升级过程 概述 相比于webpack3,webpack4可以零配置运行,打包速度比之前提高了90%,可以直接到ES6的代码进行无用代码剔除 ... 
- webstorm如何调试vue项目的js
		webstorm如何调试vue项目的js webstormvuewebstorm调试jsjs 1.编辑调试配置,新建JavaScript调试配置,并设置要访问的url地址,如下图所示: 在URL处填写 ... 
- vue项目的mode:history模式
		最近做的Vue + Vue-Router + Webpack +minitUI项目碰到的问题,在此记录一下,Vue-router 中有hash模式和history模式,vue的路由默认是hash模式, ... 
- maven(四):一个基本maven项目的pom.xml配置
		继续之前创建的test项目,一个基本项目的pom.xml文件,通常至少有三个部分 第一部分,项目坐标,信息描述等 <modelVersion>4.0.0</modelVersion& ... 
- vue 项目的I18n国际化之路
		I18n (internationalization ) ---未完善 产品国际化是产品后期维护及推广中重要的一环,通过国际化操作使得产品能更好适应不同语言和地区的需求 国际化重点:1. 语言语言本地 ... 
- Maven项目的pom.xml配置文件格式初识
		Maven项目 有pom.xml文件的项目就已经是一个maven项目了,但是还没有被maven托管,我们需要将该项目添加为maven项目 <project xmlns="http:// ... 
- java新项目的eclipse统一配置记录
		1.new java file的模版 /** * @Title:${file_name} * @Copyright: Copyright (c) 2016 * @Description: * < ... 
- 56.关于vue项目的seo问题
		不可否定的是,vue现在火.但是在实际项目中,特别是像一下交互网站,我们不可避免会考虑到的是seo问题,这直接关系到我们网站的排名,很多人说用vue搭建的网站不能做优化,那我们真的要放弃vue,放弃前 ... 
- Vue项目的npm环境搭建
		Vue项目的环境搭建主要步骤如下: vue项目创建 安装NodeJS +到官网下载自己系统对应的版本,这里我们下载Windows系统的64位zip文件,下载完成后解压,可以看到里面有一个node.ex ... 
随机推荐
- LA 3635 Pie
			题意:给出n个圆,分给n+1个人,求每个人最多能够得到多大面积的圆 二分每个人得到的圆的面积 #include<iostream> #include<cstdio> #incl ... 
- HDU 2049 不容易系列之(4)——考新郎( 错排 )
			链接:传送门 思路:错排水题,从N个人中选出M个人进行错排,即 C(n,m)*d[m] 补充:组合数C(n,m)能用double计算吗?第二部分有解释 Part 1. 分别求出来组合数的分子和分母然后 ... 
- pyqt5的QWebEngineView 使用方法
			说明1:关于QWebEngineView pyqt5 已经抛弃 QtWebKit和QtWebKitWidgets,而使用最新的QtWebEngineWidgets. QtWebEngineWidget ... 
- python中方法与函数的区别与联系
			今天huskiesir在对列表进行操作的时候,用到了sorted()函数,偶然情况下在菜鸟教程上看到了内置方法sort,同样都可以实现我对列表的排序操作,那么方法和函数有什么区别和联系呢? 如下是我个 ... 
- CVX安装使用
			CVX下载 下载地址 使用手册 Using Gurobi with CVX Using MOSEK with CVX CVX安装 下载压缩文件后解压缩至任意地址,打开matlab,进入解压缩后的地址, ... 
- 自适应增强(Adaptive Boosting)
			简介 AdaBoost,是英文”Adaptive Boosting“(自适应增强)的缩写,是一种迭代提升算法,其核心思想是针对同一个训练集训练不同的分类器(弱分类器),然后把这些弱分类器集合起来,构成 ... 
- Linux 操作系统启动流程
			1.加载bios bios中包含的硬件CPU 内存 硬盘等相关信息 2.读取MBR 读取完bios信息之后,计算机会查找bios制定的硬盘MBR引导扇区,将其内容复制到 0x7c00 地址所在的物理内 ... 
- 常用的ES6方法
			常用的ES6方法 ES6之后,新增了定义变量的两个关键字,分别是let和const. let和const都能够声明块级作用域,用法和var是类似的,let的特点是不会变量提升,而是被锁在当前块中. 实 ... 
- js数字转换为float,取N个小数
			javascript中的变量都是弱类型,所有的变量都声明为var,在类型转换过程中就没有java那么方便,它是通过 parseInt(变量).parseFloat(变量)等方法来进行类型转换的.注意: ... 
- iText操作pdf(生成,导入图片等)
			生成pdf有很多种方法,用pdfbox也很方便,今天我要写的是用iText 主要在pom.xml中配置的jar包如下 <dependency> <groupId>com.low ... 
