Получение ошибки «Ошибка: не удалось найти предустановку» env «относительно каталога» - PullRequest
0 голосов
/ 25 марта 2019

Получение этого сообщения об ошибке Error: Couldn't find preset "env" relative to directory, когда я запускаю свой проект npm run dev or npm run build

Буду очень признателен за помощь, пытаясь решить эту проблему в течение двух дней.

Error Log

ERROR in ./src/main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Couldn't find preset "env" relative to directory "/Users/marvinbenno/Documents/Code projects/the-ultimate-website"
    at /Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
    at Array.map (<anonymous>)
    at OptionManager.resolvePresets (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
    at OptionManager.mergePresets (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
    at OptionManager.mergeOptions (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
    at OptionManager.init (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/Users/marvinbenno/Documents/Code projects/the-ultimate-website/the-ultimate-website-sneaekpeak/node_modules/babel-loader/lib/index.js:50:20)
 @ multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/main.js main[2]"
./webpack.config.js

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

./package.json

{
  "name": "the-ultimate-website",
  "description": "A Vue.js project",
  "version": "1.0.0",
  "author": "Marvin <marvinkristusbenno@gmail.com>",
  "license": "MIT",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
  },
  "dependencies": {
    "@babel/polyfill": "^7.2.5",
    "babel": "^6.23.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-3": "^6.24.1",
    "bootstrap-vue": "^2.0.0-rc.14",
    "joi": "^14.3.1",
    "jshint-loader": "^0.8.4",
    "vee-validate": "^2.2.0",
    "vue": "^2.5.11",
    "vue-resource": "^1.5.1",
    "vue-router": "^3.0.2"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ],
  "devDependencies": {
    "cross-env": "^5.0.5",
    "css-loader": "^2.1.1",
    "file-loader": "^3.0.1",
    "vue-loader": "^15.7.0",
    "vue-template-compiler": "^2.4.4",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1"
  }
}

Код проекта

https://github.com/Marre1020/the-ultimate-website-sneakpeak

1 Ответ

0 голосов
/ 26 марта 2019

Прежде всего, вы не должны регистрировать каталог node_modules/ в репозитории git. Убедитесь, что вы используете .gitignore правильно.

Все ваши ошибки происходят во время сборки

Попробуйте следующие шаги, чтобы исправить ошибку, возникающую во время сборки

  • Загрузите ваш проект с вашего gitrepo и поместите его в новую папку

  • Удалить node_modules каталог

  • Установите все модули, используя npm install

  • В ваш package.json вы включили cross-env скрипт для запуска вашего проекта. Не устанавливайте это глобально. Вы должны установить эту библиотеку локально для проекта. Когда вы развертываете свой проект на любом сервере, вам нужно это cross-env, чтобы запустить ваш проект. Установите пакет cross-env как зависимость от prod. npm install --save cross-env

  • Вы включили vue-style-loader в свой webpack.config.js. Но вы не установили этот загрузчик. Установите vue-style-loader, чтобы позволить веб-пакету анализировать стили, закодированные в ваших .vue файлах npm install --save-dev vue-style-loader

  • vue-loader, который вы используете в настоящее время "vue-loader": "^15.7.0", требует, чтобы плагин был настроен в webpack.config.js. Включите VueLoaderPlugin после devtool configuration, как показано ниже.

./webpack.config.js

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

module.exports = {
   ...
  devtool: '#eval-source-map',
  plugins : [
    new VueLoaderPlugin()
  ]
}

  • Запустите ваш проект в режиме разработки npm run dev, чтобы просмотреть вывод в браузере. Предпочтителен браузер Chrome. я проигнорировал предупреждающие сообщения, генерируемые вашим кодом в консоли узла, вы должны позаботиться об этом.

Плагин Uglify вызывает несколько проблем при создании проекта для производства

npm run build

Я предлагаю вам удалить связанную конфигурацию uglifyjs из вашего webpack.config.js и протестировать ваш код в рабочем режиме. Вы можете продолжить изучение того, как решить проблему с плагином uglifyjs, или опубликовать новый вопрос.

Конфигурация Webpack без плагина uglifyjs

var path = require('path')
var webpack = require('webpack')

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

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: ['babel-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map',
  plugins : [
    new VueLoaderPlugin()
  ]
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...