VUE+Webpack搭建开发环境

版权声明:本文为博主原创文章,仅供学习交流,未经博主允许不得转载。 https://blog.csdn.net/zjy_android_blog/article/details/84493333

项目地址:https://github.com/zhongjunyao/VUE-Webpack.git

1.首先打开开发工具 Visual Studio Code ,将文件夹添加到项目,可以看到文件夹VUE-Webpack已经添加到项目中了

从控制台中进入文件夹 VUE-Webpack 中,执行 命令 npm init

PS D:\workspace\VUE-Webpack> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (vue-webpack)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\workspace\VUE-Webpack\package.json:

{
  "name": "vue-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)
PS D:\workspace\VUE-Webpack> npm i vue vue-loader css-loader  webpack --save-dev
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): EPERM: operation not permitted, scandir 'D:\workspace\VUE-Webpack\node_modules\fsevents'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
+ [email protected]
+ [email protected]
+ [email protected]
added 368 packages in 51.432s
PS D:\workspace\VUE-Webpack>

安装一下vue-template-compiler

PS D:\workspace\VUE-Webpack> npm i vue-template-compiler --save-dev
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): EPERM: operation not permitted, scandir 'D:\workspace\VUE-Webpack\node_modules\fsevents'
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 3 packages in 7.146s
PS D:\workspace\VUE-Webpack>

新建目录src,创建如图文件内容

此处我们使用了stylus,所以需要安装 stylus 的相关文件,另外我们还需要给一些css属性加上前缀,-webkit- 等,所以也要安装 postcss、autoprefixer

PS D:\workspace\VUE-Webpack> npm i stylus stylus-loader postcss --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
+ [email protected]
+ [email protected]
added 38 packages and updated 1 package in 10.856s
PS D:\workspace\VUE-Webpack> npm i autoprefixer --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 8 packages in 9.29s
PS D:\workspace\VUE-Webpack>

此外由于需要使用到 jsx 语法 和 ES6语法 等 ,需要安装 babel-plugin-syntax-jsx 、babel-loader、babel-core

PS D:\workspace\VUE-Webpack> npm i babel-plugin-syntax-jsx babel-core babel-loader --save-dev
npm WARN [email protected] requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
+ [email protected]
+ [email protected]
added 54 packages in 22.086s
PS D:\workspace\VUE-Webpack>

接下来我们需要配置三个文件.babelrc,postcss.config.js,webpack.config.js,在这个过程中我们可能需要用到其他的文件,遇到 再安装。

.babelrc文件

{
  "presets":[
    "env"
  ],
  "plugins":[
    "transform-vue-jsx"
  ]
}

postcss.config.js

const autoprefixer = require('autoprefixer');

module.exports = {
  plugins: {
    'autoprefixer': {browsers: 'last 6 version'}
  }
}

webpack.config.js

// webpack 用于打包项目的资源
const VueLoaderPlugin = require('vue-loader/lib/plugin');
// 引入html-webpack-plugin
const HTMLPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
// ExtractPlugin 将非html的资源作为单独的文件打包出来
const ExtractPlugin = require('extract-text-webpack-plugin')
const path = require('path');// 获取当前路径对象
const isDev = process.env.NODE_ENV === 'development'

const config = {
  
  // 1.声明入口路径 使用绝对路径
  // __dirname 是当前文件路径,即根目录
  // join函数将2个参数拼接为一个
  entry:path.join(__dirname,'src/index.js'),
  // 2.声明出口路径 使用绝对路径
  output:{
    filename:'bundle.[hash:8].js',
    path:path.join(__dirname,'dist')
  },
  // 3.声明使用到的插件
  plugins: [
    // 此处添加webpack.DefinePlugin使得其内的变量可以在我们的JS中访问到
    new webpack.DefinePlugin({
      'process.env':{
        NODE_ENV: isDev ? '"development"' : '"production"'
      }
    }),
    new VueLoaderPlugin(),
    new HTMLPlugin({
      title:"Vue自构建项目",// 生成html文件的标题
      filename: 'index.html', // 就是html文件的文件名,默认是index.html
      // template: 'index.html',
      inject: 'body', // script标签位于html文件的 body 底部
      // favicon:path.join(__dirname,'src/assets/images/cir_select.png'),
      meta:[
        { name:'viewport', content:'width=device-width, initial-scale=1.0,use-scalable=no' },
        { name:'keywords', content:'vue' },
        { name:'keywords', content:'webpack,构建' }
      ],
    })
  ],
  // 4.声明当前的模式 '开发' 或者 '生产'
  mode:"development",//'development' or 'production'
  // 5.声明模块规则,如指定的文件类型.vue 通过什么来加载编译
  module:{
    rules:[
      { test:/\.vue$/, loader:'vue-loader' },
      { test:/\.jsx$/, loader:'babel-loader' },
      // { test: /\.css$/, use: ["style-loader", "css-loader"] },
      { 
        test:/\.(gif|jpg|jepg|png|svg)/,
        use:[
          { 
            loader:'url-loader',
            options:{
              limit:1024,
              name:'[name]-pic.[ext]'
            }
          }
        ]
      }
      
    ]
  },
  // 6.声明编译的目标是web平台
  target:'web'

}
// 7.设置当开发环境时多一个配置项
if(isDev){
  config.devtool = '#cheap-module-eval-source-map'
  config.devServer = {
    port:8000,
    host:'0.0.0.0', // 同个局域网内别人可以访问你的电脑web页面,手机也可以访问
    overlay:{
      errors:true,//编译过程有任何的错误都显示在网页上
    },
    // open:true, // 执行dev命令自动打开页面
    hot:true,
  }
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  )
  config.module.rules.push({ 
    test:/\.styl(us)?$/,
    use:[
      {loader:'style-loader'},
      {loader:'css-loader'},
      {
        loader:'postcss-loader',
        options:{
          sourceMap:true,
        }
      },
      {loader:'stylus-loader'}
    ] 
  })
}else{
  config.entry = {
    app:path.join(__dirname,'src/index.js'),
    vendor:['vue']
  }
  config.output.filename = '[name].[chunkHash:8].js'
  config.module.rules.push({ 
    test:/\.styl(us)?$/,
    use:ExtractPlugin.extract({
      fallback:'style-loader',
      use:[
        'css-loader',
        {
          loader:'postcss-loader',
          options:{
            sourceMap:true,
          }
        },
        'stylus-loader'
      ]
    })
  })
  config.plugins.push(
    new ExtractPlugin('styles.[hash:8].css')
  )
  config.optimization = {
    splitChunks: {
      chunks: 'async',
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      automaticNameDelimiter: '~',
      name: true,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
}

module.exports = config

接下来配置package.json

{
  // ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "cross-env NODE_ENV=production webpack --config webpack.config.js",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js"
  },
  // ...
}

安装cross-env

PS D:\workspace\VUE-Webpack> npm i cross-env --save-dev
npm WARN [email protected] requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 8 packages in 13.14s
PS D:\workspace\VUE-Webpack>

上面有个警告,npm WARN [email protected] requires a peer of @babel/core@^7.0.0 but none is installed. 

我们有两种解决办法,一种是babel-loader降版本,一种是提升babel-core的版本为7

先提升babel-core版本

我们发现没有匹配的的7.0版本,只能将babel-loader降级

PS D:\workspace\VUE-Webpack> npm i cross-env babel-loader@7 --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
+ [email protected]
removed 13 packages and updated 2 packages in 10.196s
PS D:\workspace\VUE-Webpack>

为了实现开发时的热重载功能,需要安装webpack-dev-server

PS D:\workspace\VUE-Webpack> npm i webpack-dev-server --save-dev
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 165 packages in 30.003s

运行npm run dev 命令,需要安装webpack -cli

PS D:\workspace\VUE-Webpack> npm i webpack-cli -D
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 5 packages in 10.869s
PS D:\workspace\VUE-Webpack>

将webpack.config.js中使用到的插件安装 

PS D:\workspace\VUE-Webpack> npm i html-webpack-plugin --save-dev
...
+ [email protected]
updated 44 packages in 59.261s

PS D:\workspace\VUE-Webpack> npm i extract-text-webpack-plugin@^4.0.0-beta.0 --save-dev
// ...
+ [email protected]
removed 4 packages and updated 2 packages in 9.759s

PS D:\workspace\VUE-Webpack> npm i babel-plugin-transform-vue-jsx --save-dev
npm WARN [email protected] requires a peer of babel-helper-vue-jsx-merge-props@^2.0.0 but none is installed. You must install peer dependencies yourself.
...
+ [email protected]
added 1 package in 8.734s

PS D:\workspace\VUE-Webpack> npm i style-loader --save-dev
npm WARN [email protected] requires a peer of babel-helper-vue-jsx-merge-props@^2.0.0 but none is installed. You must install peer dependencies yourself.
...
+ [email protected]
added 2 packages in 9.029s

PS D:\workspace\VUE-Webpack> npm i postcss-loader babel-helper-vue-jsx-merge-props  --save-dev
...
+ [email protected]
+ [email protected]
added 1 package and updated 1 package in 9.044s

PS D:\workspace\VUE-Webpack> npm i url-loader --save-dev
...
+ [email protected]
added 3 packages in 9.992s

PS D:\workspace\VUE-Webpack> npm i css-loader --save-dev
...
+ [email protected]
updated 1 package in 11.587s

PS D:\workspace\VUE-Webpack> npm i file-loader --save-dev
...
+ [email protected]
added 2 packages in 8.552s

PS D:\workspace\VUE-Webpack> npm i babel-preset-env --save-dev
...
+ [email protected]
added 45 packages in 13.513s

运行npm run dev,在浏览器中输入http://localhost:8000/ 

开发环境配好之后,我们发布项目还需将项目打包

执行npm run build

打包之后,用浏览器打开index.html文件

猜你喜欢

转载自blog.csdn.net/zjy_android_blog/article/details/84493333