搭建基于webpack的vue环境

手动搭建基于webpack的vue环境

新建目录及基础文件

webpack-vue/
    src/
        main.js
        App.vue
    webpack.config.js    

把 package.json 做出来

npm init -y

安装相关依赖

cnpm install -D vue-loader vue-template-compiler
cnpm i -D vue
cnpm i -D vue-style-loader
cnpm i -D css-loader
cnpm i -D webpack
cnpm i -D webpack-cli
cnpm i -D babel-loader
cnpm i -D @babel/core
cnpm i -D webpack-dev-server

package.json

只有 scripts 内容是我们手动输入,其他内容都是自动生成的。

{
    "name": "webpack-vue",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "webpack-dev-server --open",
        "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@babel/core": "^7.4.0",
        "babel-loader": "^8.0.5",
        "css-loader": "^2.1.1",
        "vue": "^2.6.10",
        "vue-loader": "^15.7.0",
        "vue-style-loader": "^4.1.2",
        "vue-template-compiler": "^2.6.10",
        "webpack": "^4.29.6",
        "webpack-cli": "^3.3.0",
        "webpack-dev-server": "^3.2.1"
    }
}

webpack.config.js

const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
    mode: 'development', //production
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            // 它会应用到普通的 `.js` 文件
            // 以及 `.vue` 文件中的 `<script>` 块
            {
                test: /\.js$/,
                loader: 'babel-loader'
            },
            // 它会应用到普通的 `.css` 文件
            // 以及 `.vue` 文件中的 `<style>` 块
            {
                test: /\.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ]
            }
        ]
    },
    plugins: [
        // 请确保引入这个插件来施展魔法
        new VueLoaderPlugin()
    ],
    entry: './src/main.js',
    devServer: {
        contentBase: './dist'
    }
}

webpack-vue/dist/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <script src="./main.js"></script>
</body>
</html>

webpack-vue/src/main.js

import Vue from 'vue';
import App from './App.vue';

new Vue({
    el: "#app",
    render: h=>h(App)
})

webpack-vue/src/App.vue

<template>
    <div>
        hello {{ name }} 
        <input type="button" value="按钮" @click="fn" />
    </div>
</template>

<script>
export default {
    data(){
        return {
            name : "王杨123"
        }
    },
    methods:{
        fn(){
            alert( this.name );
        }
    }
}
</script>

<style>
div{
    color: green;
}
</style>

演示

npm run dev
npm start

webpack补充

安装

cnpm i webpack webpack-cli -g

查看版本号

webpack -v      # 4.29.6
webpack-cli -v  # 3.3.0

项目结构

首先我们创建一个目录,初始化 npm,然后 在本地安装 webpack,接着安装 webpack-cli(此工具用于在命令行中运行 webpack):

mkdir webpack-demo && cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev

文件夹、文件、及文件内容,都需要自己做。

webpack-demo/
    src/
        index.js
    index.html    

别名

output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
},
resolve:{
    alias: {
      '@': path.resolve('src'),
      '#': path.resolve('src/images'),
      'fa': path.resolve('src/fonts/font-awesome-4.7.0/css'),
    }
},
import printMe from '@/print.js'
import img from '#/1.jpg';
import 'fa/font-awesome.min.css'

不能用$当别名,修改webpack.config.js后要重新npm start

代理

devServer: { 
    contentBase: './dist',
    proxy:{
        "/api": {
            target: "https://api.wyyijiaqin.com",
            pathRewrite: { '^/api': '' },
            //secure: false,
            changeOrigin: true,
        }
    } 
},

模块热部署

监听文件的变化,如果文件有变化,可以执行一个函数

webpack.config.js

const webpack = require('webpack');

devServer: { 
    contentBase: './dist',
    //hot: true,
},
plugins: [         
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({title:'标题栏内容'}),
    //new webpack.NamedModulesPlugin(),
    //new webpack.HotModuleReplacementPlugin(), 
],

hot和后两个插件,无论是否使用,修改页面内容,浏览器都会自动刷新

index.js

import printMe from './print.js';

var span = document.createElement('span');
span.innerHTML = new Date().getSeconds();
document.body.appendChild(span)

document.onclick = function(){
    printMe('点击了body');
}
/*
if (module.hot) {
    console.log('有新东西更新了')
    module.hot.accept('./print.js', function() {
        console.log('正在接受更新的printme模块');
        printMe('热部署..123');
    })
}
*/

解开注释的代码后,一旦对应的文件有改动,这个函数就会自动执行

print.js

export default function printMe(str){ 
    console.log('789')
}

改改console.log的内容,看看页面的时间,时间变化表示页面自动刷新,其实无论是否设置热部署,页面更改,浏览器都会自动刷新,这里的热部署只能监听文件的变化。

打包时,代码是否压缩?

npm run build
output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
},
mode: "development",  //development不压缩代码; production     压缩代码,默认

post-css

cnpm i postcss-loader -D
cnpm i autoprefixer -D  # 处理css浏览器兼容

这个模块是用来处理css兼容的,会自动给css加上浏览器前缀,如-ms- -webkit- 等

style/index.css

span{
    background: red;
    color:white;
    display: flex;
    flex: 1;
    transform: translate(-50%, -50%)
}

index.js

import './style/index.css';

webpack.config.js

{
    test: /\.css$/,
    use: ['style-loader', 'css-loader', {
        loader: 'postcss-loader',
        options:{
            plugins: [
                require('autoprefixer')("last 100 versions")
            ]
        }
    }]
}

require(‘autoprefixer’)(“last 100 versions”) 参数改了就会出错。

语义:如果碰到css文件,先用style-loader和css-loader 处理,然后用postcss-loader处理,使用require引入autoprefixer模块,处理css兼容

生产环境构建

独立的 webpack.config.js 配置文件

比如我希望开发环境中,使用map,即出错时,能够看到错误内容,而生产环境下,出错时,不希望看到出错的具体内容,而且生产环境下的map还影响了文件的体积,所以应该去掉

npm install --save-dev webpack-merge
npm install --save-dev uglifyjs-webpack-plugin

通用配置 webpack.common.js

const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        app: './src/index.js'
    },
    module: {
        rules: [{
            test: /\.css$/,
            use: ['style-loader', 'css-loader', {
                loader: 'postcss-loader',
                options:{
                    plugins: [
                        require('autoprefixer')("last 100 versions")
                    ]
                }
            }]
        }]
    }, 
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            title: 'Production'
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};

开发环境的配置webpack.dev.js

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist'
    }
});

生产环境的配置webpack.prod.js

const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    plugins: [
        new UglifyJSPlugin()
    ]
});

package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --open --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
}

官方建议在生产环境下webpack.prod.js,也保留map文件,不是合并,而是一个新文件

const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    devtool: 'source-map',
    plugins: [
        new UglifyJSPlugin({
            sourceMap: true
        })
    ]
});

默认就是压缩的,所以加不加uglifyjs-webpack-plugin是一样的

process.env.NODE_ENV

plugins: [
    new UglifyJSPlugin({
        sourceMap: true
    }),
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('production')
    })
]

DefinePlugin不用写也能出效果,因为这是webpack2/3的写法,4的时候不需要了

在 /src/index.js 中输出

console.log( 'process.env.NODE_ENV:', process.env.NODE_ENV );

生产环境下运行文件时输出:

process.env.NODE_ENV: production

开发环境下运行文件是输出:

process.env.NODE_ENV: development

例外附上:

  1. gulp安装与使用
  2. 搭建基于webpack的vue环境
  3. 浅谈Vue项目优化心得
  4. 总结:搭建Vue项目心得
  5. 总结:vue中Axios的封装-API接口的管理
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值