使用webpack搭建项目运行环境出现## You are using the runtime-only build of Vue where the temp

626 阅读2分钟

这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战

报错原因

当你在项目中以这种方式导入vue时

import Vue from 'vue';

你希望项目中使用的是node_modules/vue/dist/vue.js文件 但是在最新版的Vue中,项目默认导入的是node_modules/vue/dist/vue.esm.js文件

包的查找规则

在项目根目录中有没有 node_modules文件夹

在 node_modules 中 根据包名,找到对应的vue 为文件夹

在vue 文件夹中, 找一个叫做 package.json 的包配置文件

在package.json 文件中,查找一个main属性,这个是包加载时候的入口

解决方法

1. 根据上面查找规则,找到node_modules/vue/package.json 文件,然后修改里面main配置项的值

"module": "dist/vue.js",

或者在引入vue时,可以指定路径如下

import vue from '../node_modules/vue/dist/vue.js'

2 在你的webpack.config.js配置文件中加入配置项,更改项目默认导入的vue文件为vue.js


resolve: {
    alias: {
      vue: "vue/dist/vue.js",
    },
  },

最后修改完配置不要忘了要重新运行 npm run dev,否则配置不生效

下面的是我自己搭建的webpack配置,仅供参考

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");

module.exports = {
  entry: ["@babel/polyfill", "./src/index.js"],
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  devtool: "inline-source-map",
  devServer: {
    contentBase: "./",
  },
  externals: {
    vue: "Vue",
    'vue-router': 'VueRouter',
    axios: 'axios',
    vuex: 'Vuex'
  },
  resolve: {
    alias: {
      vue: "vue/dist/vue.js",
    },
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html",
    }),
    new VueLoaderPlugin(),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ["file-loader"],
      },
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          options: {
            cacheDirectory: true,
            presets: ["@babel/preset-env"],
            plugins: ["@babel/plugin-transform-runtime"],
          },
        },
      },
    ],
  },
};

- entry

为项目的打包入口

- output

path

规定打包后的文件放哪儿,必须是绝对路径,常取值为:
__dirname+’/build’或path.resolve(__dirname,’dist’)

filename

规定打包后的文件的名字,对于单入口文件,可以取一个固定的名字,如’build.js’,对于多入口文件,要使用[name].bundle.js或[id].bundle.js来对应,其中name和id是根据多入口文件对象的属性动态确定的

- resolve

alias

创建 import 或 require 的别名,来确保模块引入变得更简单。

- module

rules:值为数组

有时还会有query或options配置,二者都是use:{options}的简写,所以在用了use后就不需要这两个配置了,(一个loader对应一个options,使用多个loader时用use):

- externals

提供了不从 bundle 中引用依赖的方式,比如vue是用script的方式从html引入的,要想在其他模块中引入的时候就可以使用这个配置

- plugins

plugins提供了loader无法完成的复杂功能