1. 程式人生 > >webpack.config.js配置遇到Error: Cannot find module '@babel/core'問

webpack.config.js配置遇到Error: Cannot find module '@babel/core'問

一、 啥問題

在配置webpack.config.js自動打包的時候,出現Error: Cannot find module '@babel/core'錯誤
最初以為是babel-core沒有安裝上。重灌了好幾遍babel-core還是不行。對照以前的專案,發現babel-loader的版本不一樣,之前的是@7.1.5版本,而現在是@8.0.0版本。

二、 解決方法

帶著半信半疑的心情安裝回@7.1.5版本

npm uninstall babel-loader
npm install babel-loader@7.1.5

npm run build發現成功了!
有點納悶,距離上次安裝不過才幾天,就更新成

[email protected]。而且還不支援原來的配置了。網上沒有找到方法解決,原理也還不清楚。先mark一下,以後解決了@8.0.0的這個問題再回來補充。

附上webpack.config.js程式碼:

var path=require('path');
var webpack=require('webpack');
var HtmlwebpackPlugin=require('html-webpack-plugin');

var ROOT_PATH=path.resolve(__dirname);
var APP_PATH=path.resolve(ROOT_PATH,'app');
var BUILD_PATH=path.resolve(ROOT_PATH,'build');

module.exports= {
    entry:{
        app: path.resolve(APP_PATH,'app.jsx')
    },
    output:{
        path:BUILD_PATH,
        filename:'bundle.js'
    },
    devtool:'eval-source-map',
    devServer: {
        historyApiFallback: true,
        hot: true,
        inline: true,
        progress: true
    },
    resolve:{
        extensions:['.js','.jsx'],
        modules: [APP_PATH, 'node_modules'],
    },
    module:{
        rules:[
           
            {
                test:/\.jsx?$/,
                loaders:['babel-loader'],
                include:APP_PATH,
            }
        ]
    },
    plugins:[
        new HtmlwebpackPlugin({
            title:'my first react app'
        })
    ]
};

在寫配置的時候 還遇到過一下錯誤:

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPresence?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
 - configuration.resolve.extensions[0] should not be empty.
   -> A non-empty string

錯誤原因:

首先 現在的module 下面應該是rules 節點,沒有loaders節點,

2.extensions: ['', '.js', '.jsx'],裡面不能包含空的元素,

3.root屬性不存在,應該替換為modules: [APP_PATH, 'node_modules'],

後面還遇到過 'use strict' is unnecessary inside of modules。的錯誤

原因是ESLint把原始碼當成了ES6的module,是不需要加use strict的,但是在Node.js中需要的,否則會提示:

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

怎麼辦呢?當然是直接斃掉這個rule,參考.eslintrc.js:

module.exports = {
  extends: "airbnb-base",
  env: {
    node: true,
    es6: true,
  },
  rules: {
    'strict': 0,
  },
};