欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue项目的webpack4.X配置

程序员文章站 2023-11-03 09:27:33
这两天摆弄webpack,躺过很多坑,直到今天看了一位博主的文章才得以解决。他对配置中的各个部分做说明。 下面的配置99.9%抄自博主: https://www.cnblogs.com/nianyifenzhizuo/p/10271001.html 安装package.json中的node-sass ......

这两天摆弄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项目的基本配置:

项目根目录:

vue项目的webpack4.X配置
{
  "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
vue项目的webpack4.X配置
module.exports = {
    loader: 'postcss-loader',
    plugins: [
        require('autoprefixer')
    ]
}
postcss.config.js
vue项目的webpack4.X配置
{
    "presets": [
        [
            "@babel/preset-env",
            {
                "modules": false
            }
        ]
    ],
    "plugins": [
        "@babel/plugin-transform-runtime", [
            "transform-remove-console",
            {
                "include": ["error", "warn"]
            }
        ]
    ]
}
.babelrc

 

 

项目根目录=>build文件夹

vue项目的webpack4.X配置
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
vue项目的webpack4.X配置
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
vue项目的webpack4.X配置
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文件夹

vue项目的webpack4.X配置
import vue from 'vue'
import router from './router/index.js'

new vue({
    el: '#app',
    router
})
index.js
vue项目的webpack4.X配置
<!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
vue项目的webpack4.X配置
<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文件夹

vue项目的webpack4.X配置
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文件夹

vue项目的webpack4.X配置
<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"
        >
          twitter
        </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
项目根目录=>src文件夹=>assets文件夹=>css
vue项目的webpack4.X配置
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