zoukankan      html  css  js  c++  java
  • 人人都能学会的webpack5搭建vue3项目(二)配置Vue

    webpack5 搭建vue3 项目 (二)

    • 安装vue以及vue-loader

      yarn add vue@next
      yarn add vue-loader@next thread-loader -D

      配置webpack.config.js

        const VueLoaderPlugin = require('vue-loader/dist/plugin').default // 需要加default, 详情可查看源码
        module.exports = {
          entry: {
            main: 'main.js'
          },
          output: {
             path: 'dist',
             filename: '[name].js',
        	 publicPath: '/'
          },
          module: {
            rules: [
              {
                test: /.js$/,
                use: [
                  'thread-loader', // 因为bable-loader比较耗时, 我们使用thread-loader来开启多线程,加快速度
                  'babel-loader'
                ]
              },
              {
                test: /.vue$/,
                loader: 'vue-loader'
              }
            ]
          }
        }
      
    • 配置babel相关
      安装babel相关loader和插件

      yarn add babel-loader @babel/core @babel/preset-env @babel/polyfill @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators @babel/plugin-proposal-object-rest-spread @babel/plugin-syntax-dynamic-import -D

      babel.config.js

        module.exports = {
          presets: [
            [
              "@babel/preset-env",
              {
                "useBuiltIns": "entry",
                module: false,
                corejs: 3
              }
            ]
          ],
          plugins: [
            ["@babel/plugin-syntax-dynamic-import"]
          ]
        }
      
    • 我们添加一下webpack-dev-server吧, 以便于我们运行,还需要安装一下html-webpack-plugin

    yarn add webpack-dev-server html-webpack-plugin -D
    修改一下webpack.config.js

      const webpack = require("webpack")
      const path = require('path')
      const VueLoaderPlugin = require('vue-loader/dist/plugin').default // 需要加default, 详情可查看源码
      const HtmlWebpackPlugin = require('html-webpack-plugin')
      const resolve = (filePath) => {
      	return path.resolve(__dirname, filePath)
      }
      module.exports = {
        entry: {
          main: resolve('src/main.js')
        },
        output: {
           path: resolve('dist'),
           filename: '[name].js',
      	 publicPath: '/'
        },
        devServer: {
          host: '0.0.0.0',
          port: 8088,
          hot: true, // 配合 Hmr使用
          historyApiFallback: true, // 设置这个原因是,当我们的vue路由设置为history模式时,如果我们当前页面位于localhost:8088/abc,这时候去刷新页面就会报错404.设置这个就是为了解决这个问题。
        },
        module: {
          rules: [
            {
              test: /.js$/,
              use: [
                'thread-loader', // 因为bable-loader比较耗时, 我们使用thread-loader来开启多线程,加快速度
                'babel-loader'
              ]
            },
            {
              test: /.vue$/,
              loader: 'vue-loader'
            }
          ]
        },
        plugins: [
           new VueLoaderPlugin(),
           new HtmlWebpackPlugin({
      	 	template: resolve('index.html'),
      		filename: 'index.html',
      		title: 'webpack5搭建vue3',
      		// icon: '', // 选择一个自己喜欢的icon添加在这吧。
      		inject: true
      	 }),
           new webpack.HotModuleReplacementPlugin()
        ]
      }
    

    我们还需要加一个index.html的页面, 在根目录下吧

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
      <div id="app"></div>
    </body>
    </html>
    

    然后我们更改一下根目录下的package.json文件的scripts脚本

     {
        "scripts": {
            "dev": "webpack-dev-server --config webpack.config.js --inline --progress"
         }
      }
    

    这样我们就能在命令行中使用 yarn dev 来运行我们的项目了
    接下来我们在src目录下新建一个App.vue文件

      <template>
      	我是Vue项目啊 {{username}}
      </template>
      <script>
      	import {ref} from 'vue'
      	export default {
      		setup () {
      			let username = ref('helloworld')
      			return {
      				username
      			}
      		}
      	}
      </script>
    

    现在我们打开src目录下的main.js文件

      import {createApp} from 'vue'
      import App from './App.vue'
      const app = createApp()
      app.mount('#app')
    

    这时候我们到根目录下按住shift 加鼠标右键, 选择在此处打开命令窗口, 输入 yarn dev,敲回车,等待项目启动,这时候不出意外应该会报错。报错信息应该是这样子的。

    sealing module hashing(node:8616) UnhandledPromiseRejectionWarning: TypeErro
    r [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an insta
    nce of Buffer, TypedArray, or DataView. Received undefined
      at Hash.update (internal/crypto/hash.js:82:11)
      at BulkUpdateDecorator.update (E:studywebfrontWebpackwebpack5_vue3
    ode_m
    oduleswebpacklibutilcreateHash.js:51:14)
      at NormalModule.updateHash (E:studywebfrontWebpackwebpack5_vue3
    ode_modu
    leswebpacklibNormalModule.js:1191:8)
      at Compilation._createModuleHash (E:studywebfrontWebpackwebpack5_vue3
    od
    e_moduleswebpacklibCompilation.js:3097:10)
      at Compilation.createModuleHashes (E:studywebfrontWebpackwebpack5_vue3
    o
    de_moduleswebpacklibCompilation.js:3069:10)
      at E:studywebfrontWebpackwebpack5_vue3
    ode_moduleswebpacklibCompilati
    on.js:2346:11
    ....
    

    这是因为缺少@vue/compiler-sfc, 这时候我们安装一下他。

    yarn add @vue/compiler-sfc -D

    之所以要安装它,是因为我们的vue-loader现在依赖于他,我们可以发现之前的vue-template-compiler 这个模板编译器不用了,也就是被@vue/compiler-sfc 替代了。
    安装完毕我们再次运行 yarn dev ,等待项目启动, 我们在浏览器输入localhost:8088, 就可以看到我们的页面了。

    后面肯定还会遇到问题(比如webpack5的热更新,设置了不生效,我们需要在webpack配置中把target的值改为'web'), 如果大家遇到问题,请抛出来我们一起解决。多谢各位乐于分享的兄弟们。

    这里分享一下我遇到的问题

    Error: Cannot find module 'webpack-cli/bin/config-yargs'
    Require stack:
    - E:studywebfrontWebpackwebpack5_vue3
    ode_moduleswebpack-dev-serverinweb
    pack-dev-server.js
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
        at Function.Module._load (internal/modules/cjs/loader.js:842:27)
        at Module.require (internal/modules/cjs/loader.js:1026:19)
        at require (internal/modules/cjs/helpers.js:72:18)
        at Object.<anonymous> (E:studywebfrontWebpackwebpack5_vue3
    ode_modulesw
    ebpack-dev-serverinwebpack-dev-server.js:65:1)
        at Module._compile (internal/modules/cjs/loader.js:1138:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
        at Module.load (internal/modules/cjs/loader.js:986:32)
        at Function.Module._load (internal/modules/cjs/loader.js:879:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js
    :71:12) {
      code: 'MODULE_NOT_FOUND',
      requireStack: [
        'E:\studywebfront\Webpack\webpack5_vue3\node_modules\webpack-dev-server
    \bin\webpack-dev-server.js'
      ]
    

    遇到这个问题, 将webpack-cli 换成低版本即可 webpack-cli@3.3.12

    github地址: https://github.com/ComponentTY/webpack5-vue3
    webpack5搭建vue3给个星吧,大佬们,github上面的是已经搭建好的,并正应用于自己公司内部项目中。

  • 相关阅读:
    如何输出高精度时间差
    GetThreadTimes获取其它线程cpu时间
    12-Python基础之类与面向对象
    10-Python函数之递归
    09-Python基础之内置函数与匿名函数
    08-Python基础之迭代器与生成器
    07-Python基础之装饰器
    06-Python基础之函数进阶(嵌套,作用域)
    05-Python基础之函数基础
    04-Python基础之文件操作基础
  • 原文地址:https://www.cnblogs.com/0915ty/p/14549864.html
Copyright © 2011-2022 走看看