当前位置:首页 >> 网络编程

babel7.x和webpack4.x配置vue项目的方法步骤

很偶然的今天想开个自己的小项目,记录一下最近项目工程上实现的一个小交互。按照之前运行非常流畅的配置走一遍,打包遇到各种坑。只好根据命令行的报错逐个排查,发现babel升级了一个大版本,已经到7.x了。看来每日沉迷项目,已经跟不上节奏了。这里记录一下遇到的问题以及解决方案。

1.webpack 4.x 插件 extract-text-webpack-plugin

(node:2628) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
i "htmlcode">
const MiniCssExtractPlugin = require("mini-css-extract-plugin") ;

const config = module.exports = {

   plugins: [
     new MiniCssExtractPlugin({
      filename: "[name].[chunkhash:8].css",
       chunkFilename: "[id].css"
      })
   ],

   module: {
    rules: [
      {
      test: /\.css$/,
      use: [
         MiniCssExtractPlugin.loader,
          "css-loader"
       ]
     }
    ]
    }
}

module.exports = config

2.babel 升级 6.x 到 7.x

(1) @babel/core

Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). 
 If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.

没找到 @babel/core ,这里把 babel-core 卸载,并安装 @babel/core 。

npm un babel-core
npm i -D @babel/core

(2) @babel/preset-*

Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin/Preset files are not allowed to export objects, only functions.

将 babel-preset-* 卸载,重新安装 @babel/preset-* ,并且修改 .babelrc 中的 presets

npm:
- babel-preset-env
+ @babel/perset-env

.babelrc:
- "presets": ["env"]
+ "presets": ["@babel/preset-env"]

另,stage-*已弃用

(3) @babel/plugin-*

Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: this.setDynamic is not a function
  at PluginPass.pre
  ...

这次是插件了,一样把babel-plugin-*卸载,重新安装@babel/plugin-*

然后修改.babelrc文件

具体的包名可以在 npm仓库 里找

(4) 最终文件

.babelrc
{
  "presets": ["@babel/preset-env"],
  "plugins": [
      "@babel/plugin-transform-runtime"
  ]
}

package.json
"devDependencies": {
  "@babel/core": "^7.1.2",
  "@babel/plugin-transform-runtime": "^7.1.0",
  "@babel/preset-env": "^7.1.0",
  "babel-loader": "^8.0.4",
  
  ...
 },
"dependencies": {
  "@babel/runtime": "^7.1.2",
  "vue": "^2.5.17",
  "vue-loader": "^15.4.2",
  "vue-router": "^3.0.1",
  "vuex": "^3.0.1",
  "webpack": "^4.22.0",
  "webpack-cli": "^3.1.2",
  "webpack-dev-server": "^3.1.10",
  "webpack-merge": "^4.1.4"
  ...
 }

(5) 总结

babel 舍弃了以前的 babel-*-* 的命名方式,改成了 @babel/*-*

修改依赖和 .babelrc 文件后就能正常启动项目了。

3.vue-loader 15.x vueLoaderPlugin

vue-loader was used without the corresponding plugin. 
Make sure to include VueLoaderPlugin in your webpack config.
//两个方式都可以的,随便用一个

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

// 或者 

const { VueLoaderPlugin } = require('vue-loader');


plugins: [
  // make sure to include the plugin for the magic
  new VueLoaderPlugin()
]

详细 https://github.com/vuejs/vue-loader/issues/1238

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。