Error for the selected environment is no default script chunk format available

When I run the script for "webpack-dev-server --config webpack.dev.js", I get this error: Error: For the selected environment is no default script chunk format available: JSONP Array push...

When I run the script for «webpack-dev-server —config webpack.dev.js», I get this error:

Error: For the selected environment is no default script chunk format available:
JSONP Array push can be chosen when ‘document’ or ‘importScripts’ is available.
CommonJs exports can be chosen when ‘require’ or node builtins are available.
Make sure that your ‘browserslist’ includes only platforms that support these features or select an appropriate ‘target’ to allow selecting a chunk format by default. Alternatively specify the ‘output.chunkFormat’ directly.

What is this error? These are the files in my project directory:

index.html 

<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="./dist/main.css" />
  <title>Project Name</title>
</head>

<body>
  <script src="./dist/main.js"></script>
</body>

</html>
package.json

{
  "name": "js",
  "version": "1.0.0",
  "description": "Browser 2D game ",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --config webpack.dev.js",
    "webpack:watch": "webpack --watch --config webpack.dev.js",
    "webpack:build": "webpack --config webpack.prod.js  --optimize-minimize"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": ""
  },
  "browserslist": [
    "last 1 version",
    "> 1%",
    "maintained node versions",
    "not dead"
  ],
  "homepage": "",
  "devDependencies": {
    "@babel/core": "^7.15.5",
    "@babel/plugin-proposal-optional-chaining": "^7.14.5",
    "@babel/preset-env": "^7.15.6",
    "autoprefixer": "^10.3.7",
    "babel-loader": "^8.2.2",
    "css-loader": "^6.3.0",
    "fibers": "^5.0.0",
    "file-loader": "^6.2.0",
    "mini-css-extract-plugin": "^2.3.0",
    "postcss-loader": "^6.1.1",
    "sass": "^1.42.1",
    "sass-loader": "^12.1.0",
    "style-loader": "^3.3.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.56.1",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "^4.3.1",
    "webpack-merge": "^5.8.0"
  }
}
postcss.config.js

module.exports = {
    plugins: {
        autoprefixer: {}
    }
};
webpack.common.js

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const outputDir = "./dist";

module.exports = {
  entry: path.resolve(__dirname, "src", "index.js"), 
  output: {
    path: path.join(__dirname, outputDir),
    filename: "[name].js",
    publicPath: "/dist/",
  },
  resolve: {
    extensions: [".js"], // if we were using React.js, we would include ".jsx"
  },
  module: {
    rules: [
      {
        test: /.js$/, // if we were using React.js, we would use .jsx?$/
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
            plugins: ["@babel/plugin-proposal-optional-chaining"],
            exclude: /node_modules/,
          }, // if we were using React.js, we would include "react"
        },
      },
      {
        test: /.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: "../",
            },
          },
          "css-loader",
          "postcss-loader",
        ],
      },
      {
        test: /.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: "file-loader",
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              name: "[name].[ext]",
              outputPath: "images/",
              publicPath: "images/",
            },
          },
        ],
      },
      {
        test: /.s[ca]ss/i,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: "../",
            },
          },
          "css-loader",
          "resolve-url-loader",
          {
            loader: "sass-loader", 
            options: {
              implementation: require('sass')
            }
          },
          "postcss-loader",
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // all options are optional
      filename: "[name].css",
      chunkFilename: "[id].css",
      ignoreOrder: false, // Enable to remove warnings about conflicting order
    }),
    require("autoprefixer"),
  ],
};
webpack.dev.js

const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");

module.exports = merge(common, {
  mode: "development",
  devtool: "inline-source-map",
  devServer: {
    contentBase: "./",
    watchContentBase: true,
    open: true, // use "chrome" for PC
  },
});
webpack.prod.js

const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");

module.exports = merge(common, {
  mode: "development",
  devtool: "inline-source-map",
  devServer: {
    contentBase: "./",
    watchContentBase: true,
    open: true, // use "chrome" for PC
  },
});

Mouaadouk302

yarn start failed after upgrading

i have upgraded react-scripts to v5 and node to v16 & i get error when starting the project knowing that I have reinstalled node_modules.

image (1)

output :
yarn run v1.22.5
$ react-scripts start
Failed to compile.

For the selected environment is no default script chunk format available:
JSONP Array push can be chosen when ‘document’ or ‘importScripts’ is available.
CommonJs exports can be chosen when ‘require’ or node builtins are available.
Make sure that your ‘browserslist’ includes only platforms that support these features or select an appropriate ‘target’ to allow selecting a chunk format by default. Alternatively specify the ‘output.chunkFormat’ directly.

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

raix

Hi @Mouaadouk302 thanks for reporting,
Try removing your lockfile and delete node_modules again, then install to see if the issue is fixed

Please add steps to replicate the issue or better a repository replicating the issue

gnowland

Remove any mention of node from your browserslist entry in package.json. That fixed it for me.

olawalejuwonm

removing browserslist and allowing the command to use the default one works for me

suraj5969

removing browserslist and allowing the command to use the default one works for me

worked for me. Thanks @olawalejuwonm

for others,
Just delete the browserslist object form your packege.json and run command again

webpack.config.js

'use strict';

let path = require('path');

module.exports = {
mode: 'development',
entry: './src/js/script.js',
output: {
filename: 'bundle.js',
path: __dirname + './dist/js'
},
watch: true,

devtool: "source-map",

module: {}
};

package.json

{
"name": "kredo-bet",
"version": "1.0.0",
"main": "gulpfile.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"browser-sync": "^2.26.12",
"gulp": "^4.0.2",
"gulp-autoprefixer": "^6.1.0",
"gulp-clean-css": "^4.3.0",
"gulp-cli": "^2.3.0",
"gulp-htmlmin": "^5.0.1",
"gulp-imagemin": "^6.2.0",
"gulp-rename": "^1.4.0",
"gulp-sass": "^4.1.0",
"webpack": "^5.42.1",
"webpack-cli": "^4.7.2"
},
"browserslist": [
"last 1 version",
"> 1%",
"maintained node versions",
"not dead"
],
"description": "",
"dependencies": {}
}

menu.js

function hamburgerNenu() {
const hamburger = document.querySelector('.header__gamburger'),
closeElem = document.querySelector('.menu__toggle'),
menu = document.querySelector('.menu');

hamburger.addEventListener('click', () => {
menu.classList.add('active');
});

closeElem.addEventListener('click', () => {
menu.classList.remove('active');
});
}

export default hamburgerNenu;

script.js

import hamburger from './modules/menu';

hamburger();

The error looks like this: Error: For the selected environment is no default script chunk format available: JSONP Array push can be chosen when ‘document’ or ‘importScripts’ is available. CommonJs exports can be chosen when ‘require’ or node builtins are available. Make sure that your ‘browserslist’ includes only platforms that support these features or select an appropriate ‘target’ to allow selecting a chunk format by default. Alternatively specify the ‘output.chunkFormat’ directly. at E:workkredo-betnode_moduleswebpacklibconfigdefaults.js:669:11 at F (E:workkredo-betnode_moduleswebpacklibconfigdefaults.js:71:15) at applyOutputDefaults (E:workkredo-betnode_moduleswebpacklibconfigdefaults.js:650:2) at applyWebpackOptionsDefaults (E:workkredo-betnode_moduleswebpacklibconfigdefaults.js:182:2) at createCompiler (E:workkredo-betnode_moduleswebpacklibwebpack.js:78:2) at create (E:workkredo-betnode_moduleswebpacklibwebpack.js:127:16) at webpack (E:workkredo-betnode_moduleswebpacklibwebpack.js:135:47) at WebpackCLI.f [as webpack] (E:workkredo-betnode_moduleswebpacklibindex.js:55:16) at WebpackCLI.createCompiler (E:workkredo-betnode_moduleswebpack-clilibwebpack-cli.js:2053:29) at async WebpackCLI.buildCommand (E:workkredo-betnode_moduleswebpack-clilibwebpack-cli.js:2173:20)0)

Я пытаюсь добавить Cypress в очень простой CRA, но у меня возникают проблемы с тем, что Cypress может понимать файлы .scss.

Когда я запускаю npm run cypress для запуска теста, я получаю следующую ошибку:

Error: Webpack Compilation Error
./src/App.scss 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .app {
|   align-items: center;
|   display: flex !important;
 @ ./src/App.jsx 28:0-21
 @ ./cypress/integration/App.spec.js
...

Кажется, что загрузчик sass не используется, когда Cypress пытается смонтировать компонент? Как я могу исправить это?

Пакет.json:

{
  "name": "cypress_test",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "cypress": "cypress open",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "dependencies": {
    "@cypress/react": "^5.12.4",
    "@cypress/webpack-dev-server": "^1.8.4",
    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@fontsource/roboto": "^4.5.5",
    "@mui/icons-material": "^5.6.2",
    "@mui/material": "^5.6.3",
    "@mui/styled-engine-sc": "^5.6.1",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^12.1.5",
    "@testing-library/user-event": "^13.5.0",
    "cypress": "^9.6.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.1",
    "sass": "^1.51.0",
    "styled-components": "^5.3.5",
    "web-vitals": "^2.1.4"
  },
  "devDependencies": {
    "@babel/core": "^7.17.9",
    "@babel/preset-env": "^7.16.11",
    "@cypress/webpack-preprocessor": "^5.11.1",
    "babel-loader": "^8.2.5",
    "eslint-plugin-cypress": "^2.12.1",
    "html-webpack-plugin": "^4.5.2",
    "webpack": "^5.72.0"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "overrides": [
    {
      "extends": [
        "plugin:cypress/recommended"
      ],
      "files": [
        "cypress/**/*.js"
      ]
    }
  ],
  "resolutions": {
    "@mui/styled-engine": "npm:@mui/styled-engine-sc@latest"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "jest": {
    "coveragePathIgnorePatterns": [
      "<rootDir>/cypress/"
    ]
  }
}

App.spec.js:

import React from 'react';
import data from '../fixtures/data.json';
import App from '../../src/App.jsx';

describe('Test search functionality', () => {
  beforeEach(() => {
    cy.mount(<App />);
  });

  it('renders new fact when search is performed', () => {
    cy.visit('http://localhost:3001')
    // Type in search input
    cy.get('input').type('Test');

    // Click on search button
    cy.get('.submit-btn').click();

    // Intercept the request and return the mock data
    cy
      .intercept({
        method: 'GET',
        url: `${process.env.REACT_APP_API_ENDPOINT}/jokes/search?query=Test`
      }, {
        fixture: data.result[1]
      })
      .as('fetchFact');

    // cy.wait(['@fetchFact']);

    cy.get('p.copy').should('contain', data.result[1].value);
  })
});

Кипарис/плагины/index.js:

const injectDevServer = require('@cypress/react/plugins/react-scripts');

module.exports = (on, config) => {
  injectDevServer(on, config);
  return config;
};

Обновлено:
Попробовав предложенное ниже решение с изменениями в файле plugins/index.js, я получаю новую ошибку:

Error: For the selected environment is no default script chunk format available:
JSONP Array push can be chosen when 'document' or 'importScripts' is available.
CommonJs exports can be chosen when 'require' or node builtins are available.
Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly.

Обновлен /cypress/plugins/index.js:

const findWebpack = require('find-webpack')
const webpackPreprocessor = require('@cypress/webpack-preprocessor');
const injectDevServer = require('@cypress/react/plugins/react-scripts');

module.exports = (on, config) => {
  const webpackOptions = findWebpack.getWebpackOptions();

  if (!webpackOptions) {
    throw new Error('Could not find Webpack in this project');
  }

  const cleanOptions = { reactScripts: true };

  findWebpack.cleanForCypress(cleanOptions, webpackOptions);

  const options = {
    webpackOptions,
    watchOptions: {},
  };

  on('file:preprocessor', webpackPreprocessor(options));
  injectDevServer(on, config);
  return config;
};

Я также удалил ключ browserslist из моего package.json.

J., 27 апреля 2022 г., 23:40

96

1

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error code 3 the nvidia opengl driver detected
  • Error for site owner invalid key type как исправить
  • Error code 3 premier pro
  • Error for site owner invalid domain for site key что делать
  • Error code 2s129 1

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии