### Start Application Source: https://github.com/dilanx/craco/blob/main/website/docs/getting-started.md Start your application using the npm start command after configuring CRACO. ```bash npm start ``` -------------------------------- ### Install Dependencies Source: https://github.com/dilanx/craco/blob/main/website/README.md Installs project dependencies using Yarn. ```bash yarn ``` -------------------------------- ### Start Local Development Server Source: https://github.com/dilanx/craco/blob/main/website/README.md Starts a local development server for live preview of changes. Most changes are reflected live without server restart. ```bash yarn start ``` -------------------------------- ### Example of throwUnexpectedConfigError output Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/miscellaneous.md This example shows the typical error output when `throwUnexpectedConfigError` is invoked due to a missing loader in the webpack configuration. ```bash $ yarn start yarn run v1.12.3 $ craco start /path/to/your/app/craco.config.js:23 throw new Error( ^ Error: Can't find eslint-loader in the webpack config! This error probably occurred because you updated react-scripts or craco. Please try updating craco-less to the latest version: $ yarn upgrade craco-less Or: $ npm update craco-less If that doesn't work, craco-less needs to be fixed to support the latest version. Please check to see if there's already an issue in the ndbroadbent/craco-less repo: * https://github.com/DocSpring/craco-less/issues?q=is%3Aissue+webpack+eslint-loader If not, please open an issue and we'll take a look. (Or you can send a PR!) You might also want to look for related issues in the craco and create-react-app repos: * https://github.com/dilanx/craco/issues?q=is%3Aissue+webpack+eslint-loader * https://github.com/facebook/create-react-app/issues?q=is%3Aissue+webpack+eslint-loader at throwUnexpectedConfigError (/path/to/your/app/craco.config.js:23:19) ... ``` -------------------------------- ### Install Craco CLI Source: https://github.com/dilanx/craco/blob/main/packages/craco/README.md Install the latest version of Craco as a development dependency using npm. ```bash npm i -D @craco/craco ``` -------------------------------- ### Define PostCSS Configuration Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-a-postcss-config-file.md Define your PostCSS plugins and their configurations in `postcss.config.js`. This example includes `postcss-flexbugs-fixes` and `postcss-preset-env`. ```javascript module.exports = { plugins: [ require('postcss-flexbugs-fixes'), require('postcss-preset-env')({ autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'nesting-rules': true, }, }), ], }; ``` -------------------------------- ### Install TypeScript Types Source: https://github.com/dilanx/craco/blob/main/website/docs/getting-started.md Install the official CRACO typings as a development dependency for type checking and IDE autocompletion. ```bash npm i -D @craco/types ``` -------------------------------- ### Configure Craco Plugin with Options Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/hooks.md This example demonstrates how to include a custom plugin, like the `craco-log-plugin`, in your `craco.config.js` file and pass specific options to it. ```javascript const logPlugin = require('./craco-log-plugin'); module.exports = { // ... plugins: [ { plugin: logPlugin, options: { preText: 'WEBPACK CONFIG' }, }, ], }; ``` -------------------------------- ### Craco Style Configuration Example Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/style.md This snippet shows the structure for configuring style-related options in craco.config.js, including CSS modules, CSS, Sass, and PostCSS. ```javascript module.exports = { // ... style: { modules: { localIdentName: '', }, css: { loaderOptions: { /* ... */ }, loaderOptions: (cssLoaderOptions, { env, paths }) => { /* ... */ return cssLoaderOptions; }, }, sass: { loaderOptions: { /* ... */ }, loaderOptions: (sassLoaderOptions, { env, paths }) => { /* ... */ return sassLoaderOptions; }, }, postcss: { mode: 'extends' /* (default value) */ || 'file', plugins: [require('plugin-to-append')], plugins: (plugins) => [require('plugin-to-prepend')].concat(plugins), env: { autoprefixer: { /* ... */ }, stage: 3, features: { /* ... */ }, }, loaderOptions: { /* ... */ }, loaderOptions: (postcssLoaderOptions, { env, paths }) => { /* ... */ return postcssLoaderOptions; }, }, }, }; ``` -------------------------------- ### Exporting Craco Configuration as Object Literal Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/getting-started.md A basic example of exporting Craco configuration using a simple JavaScript object literal. ```javascript module.exports = { ... }; ``` -------------------------------- ### Implement overrideWebpackConfig Hook Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/hooks.md This example shows how to use the `overrideWebpackConfig` hook to log plugin options and the Webpack configuration. It demonstrates accessing `webpackConfig`, `cracoConfig`, `pluginOptions`, and `context`. ```javascript module.exports = { overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions, context: { env, paths }, }) => { if (pluginOptions.preText) { console.log(pluginOptions.preText); } console.log(JSON.stringify(webpackConfig, null, 4)); return webpackConfig; }, }; ``` -------------------------------- ### Configure PostCSS Features in craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/add-postcss-features.md Use this configuration to enable specific PostCSS features. This example enables nesting rules. ```javascript module.exports = { style: { postcss: { env: { stage: 3, features: { 'nesting-rules': true, }, }, }, }, }; ``` -------------------------------- ### Update package.json Scripts Source: https://github.com/dilanx/craco/blob/main/packages/craco/README.md Modify the `scripts` section in `package.json` to use the `craco` CLI instead of `react-scripts` for starting, building, and testing. ```diff "scripts": { - "start": "react-scripts start" + "start": "craco start" - "build": "react-scripts build" + "build": "craco build" - "test": "react-scripts test" + "test": "craco test" } ``` -------------------------------- ### Get First Asset Module by Name Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Retrieves the first Webpack asset module that matches the provided name. Useful for targeted modifications. ```javascript const { getAssetModule, assetModuleByName } = require('@craco/craco'); const { isFound, match } = getAssetModule( webpackConfig, assetModuleByName('asset/source') ); if (isFound) { // do stuff... } ``` -------------------------------- ### Craco ESLint Configuration Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/eslint.md Example of how to configure ESLint settings within the craco.config.js file. This snippet shows the structure for enabling ESLint and setting its mode, along with placeholders for custom configurations and plugin options. ```javascript module.exports = { // ... eslint: { enable: true /* (default value) */, mode: 'extends' /* (default value) */ || 'file', configure: { /* ... */ }, configure: (eslintConfig, { env, paths }) => { /* ... */ return eslintConfig; }, pluginOptions: { /* ... */ }, pluginOptions: (eslintPluginOptions, { env, paths }) => { /* ... */ return eslintPluginOptions; }, }, }; ``` -------------------------------- ### Get All Asset Modules by Name Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Retrieves all Webpack asset modules that match the provided name. Useful for bulk operations. ```javascript const { getAssetModules, assetModuleByName } = require('@craco/craco'); const { hasFoundAny, matches } = getAssetModules( webpackConfig, assetModuleByName('asset/inline') ); if (hasFoundAny) { matches.forEach((x) => { // do stuff... }); } ``` -------------------------------- ### CRACO Plugin Structure Example Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/getting-started.md This JavaScript code demonstrates the basic structure of a CRACO plugin, including the four optional hooks: overrideCracoConfig, overrideWebpackConfig, overrideDevServerConfig, and overrideJestConfig. Each hook receives a configuration object and must return the updated configuration. ```javascript module.exports = { overrideCracoConfig: ({ cracoConfig, pluginOptions, context }) => { /* ... */ return cracoConfig; }, overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions, context, }) => { /* ... */ return webpackConfig; }, overrideDevServerConfig: ({ devServerConfig, cracoConfig, pluginOptions, context, }) => { /* ... */ return devServerConfig; }, overrideJestConfig: ({ jestConfig, cracoConfig, pluginOptions, context }) => { /* ... */ return jestConfig; }, }; ``` -------------------------------- ### Get a Webpack Plugin by Name Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-plugins.md Retrieve the first Webpack plugin that matches the provided name using `getPlugin` and `pluginByName`. This is useful for inspecting or modifying existing plugins. ```js const { getPlugin, pluginByName } = require('@craco/craco'); const { isFound, match } = getPlugin( webpackConfig, pluginByName('ESLintWebpackPlugin') ); if (isFound) { // do stuff... } ``` -------------------------------- ### Configure Craco for Linaria Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-linaria.md Add the craco-linaria plugin to your craco.config.js file to enable Linaria integration. This setup is required for Linaria to process your styled components. ```javascript module.exports = { plugins: [{ plugin: require('craco-linaria') }], }; ``` -------------------------------- ### Generate Jest Configuration Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration-api.md Use `createJestConfig` to generate a Jest configuration object based on your CRACO configuration. This is useful for integrating custom Jest setups with CRACO. ```javascript const { createJestConfig } = require('@craco/craco'); const cracoConfig = require('./craco.config.js'); const jestConfig = createJestConfig(cracoConfig); module.exports = jestConfig; ``` -------------------------------- ### Craco Configuration for PureScript Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-purescript.md Configure craco.config.js to add the `purs-loader` for PureScript files. This setup resolves `.purs` extensions, bypasses the ModuleScopePlugin for broader import possibilities, and configures the loader with Spago and pscIde options. ```javascript // Use PureScript in React Application // const { addBeforeLoader, loaderByName } = require('@craco/craco'); const path = require('path'); // Detect watch // const isWatch = process.argv.some((a) => a === '--watch'); const isWebpackDevServer = process.argv.some( (a) => path.basename(a) === 'webpack-dev-server' ); module.exports = { webpack: { configure: (webpackConfig) => { const { resolve } = webpackConfig; // Resolve purescript extension resolve.extensions.push('.purs'); // Allow imports outside of `src` folder for purescript dependencies webpackConfig.resolve.plugins = resolve.plugins.filter( ({ constructor: c }) => !c || c.name !== 'ModuleScopePlugin' ); // PureScript loader const pursLoader = { loader: 'purs-loader', test: /\.purs$/, exclude: /node_modules/, query: { src: ['src/**/*.purs'], spago: true, pscIde: true, watch: isWebpackDevServer || isWatch, }, }; // Append purs-loader before file-loader addBeforeLoader(webpackConfig, loaderByName('file-loader'), pursLoader); return webpackConfig; }, }, }; ``` -------------------------------- ### Craco Configuration for CSS Modules Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-babel-plugin-react-css-modules.md This snippet shows the craco.config.js setup to enable babel-plugin-react-css-modules. It defines a localIdentName for CSS modules and configures the plugin with custom attribute names. ```javascript const CSS_MODULE_LOCAL_IDENT_NAME = '[local]___[hash:base64:5]'; module.exports = { style: { modules: { localIdentName: CSS_MODULE_LOCAL_IDENT_NAME, }, }, babel: { plugins: [ [ 'babel-plugin-react-css-modules', { generateScopedName: CSS_MODULE_LOCAL_IDENT_NAME, attributeNames: { activeStyleName: 'activeClassName' }, }, ], ], }, }; ``` -------------------------------- ### Generate Webpack Development Configuration Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration-api.md Use `createWebpackDevConfig` to generate a Webpack development configuration object. This allows you to leverage CRACO's configuration within your Webpack setup for development environments. ```javascript const { createWebpackDevConfig } = require('@craco/craco'); const cracoConfig = require('./craco.config.js'); const webpackConfig = createWebpackDevConfig(cracoConfig); module.exports = webpackConfig; ``` -------------------------------- ### Webpack Configuration with Function Override Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/getting-started.md Example of overriding webpack configuration using a function in craco.config.js. The function receives the original webpack config and context, returning the modified config. ```javascript module.exports = { webpack: { configure: (webpackConfig, { env, paths }) => { webpackConfig.entry = './path/to/my/entry/file.js'; return webpackConfig; }, }, }; ``` -------------------------------- ### Configure craco.config.js for html-loader Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-html-loader.md Add `html-loader` to your Craco project to process HTML files. Ensure `html-loader` is installed as a dev dependency. This configuration adds the loader before `file-loader` and sets up the necessary file extensions. ```javascript /** * To use this, ensure you have added `html-loader` as a dev dependency in your `package.json` first * Learn more: https://github.com/webpack-contrib/html-loader */ const { loaderByName, addBeforeLoader } = require('@craco/craco'); module.exports = { webpack: { configure: (webpackConfig) => { webpackConfig.resolve.extensions.push('.html'); const htmlLoader = { loader: require.resolve('html-loader'), test: /\.html$/, exclude: /node_modules/, }; addBeforeLoader(webpackConfig, loaderByName('file-loader'), htmlLoader); return webpackConfig; }, }, }; ``` -------------------------------- ### Build Static Website Source: https://github.com/dilanx/craco/blob/main/website/README.md Generates static website content into the 'build' directory for hosting. ```bash yarn build ``` -------------------------------- ### Build Application Source: https://github.com/dilanx/craco/blob/main/website/docs/getting-started.md Build your application using the npm run build command after configuring CRACO. ```bash npm run build ``` -------------------------------- ### Add Craco Configuration File Source: https://github.com/dilanx/craco/blob/main/packages/craco/README.md Create a `craco.config.js` file at the root of your project to begin configuring Craco. ```diff my-app ├── node_modules + ├── craco.config.js └── package.json ``` -------------------------------- ### Adding and Removing Webpack Plugins Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/webpack.md Demonstrates how to add and remove Webpack plugins. Plugins can be prepended or appended, and their constructor names can be used for removal. ```javascript const CopyPlugin = require('copy-webpack-plugin'); const ESLintPlugin = require('eslint-webpack-plugin'); const HtmlPlugin = require('html-webpack-plugin'); module.exports = { webpack: { plugins: { add: [ new CopyPlugin() /* this plugin will be prepended */, [new ESLintPlugin(), 'prepend'] /* this one, too */, [new HtmlPlugin(), 'append'] /* not this one though */, ], }, }, }; ``` -------------------------------- ### Get All Loaders by Name Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-loaders.md Use `getLoaders` with `loaderByName` to find all occurrences of a specific loader in the Webpack configuration. ```javascript const { getLoaders, loaderByName } = require('@craco/craco'); const { hasFoundAny, matches } = getLoaders( webpackConfig, loaderByName('babel-loader') ); if (hasFoundAny) { matches.forEach((x) => { // do stuff... }); } ``` -------------------------------- ### Deploy Website (SSH) Source: https://github.com/dilanx/craco/blob/main/website/README.md Deploys the website using SSH, typically for GitHub Pages hosting. ```bash USE_SSH=true yarn deploy ``` -------------------------------- ### Get First Loader by Name Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-loaders.md Use `getLoader` with `loaderByName` to find the first occurrence of a specific loader in the Webpack configuration. ```javascript const { getLoader, loaderByName } = require('@craco/craco'); const { isFound, match } = getLoader( webpackConfig, loaderByName('eslint-loader') ); if (isFound) { // do stuff... } ``` -------------------------------- ### Deploy Website (No SSH) Source: https://github.com/dilanx/craco/blob/main/website/README.md Deploys the website without using SSH, requiring your GitHub username. ```bash GIT_USER= yarn deploy ``` -------------------------------- ### craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-dart-sass.md Configure the sass-loader to use Dart Sass. This setup ensures Dart Sass is prioritized and includes a workaround for a webpack-loader issue. ```javascript /** * This example shows how to configure the sass-loader for Dart Sass. * Note: Only Dart Sass ('sass') currently supports @use. */ module.exports = { style: { sass: { loaderOptions: { // Prefer 'sass' (dart-sass) over 'node-sass' if both packages are installed. implementation: require('sass'), // Workaround for this bug: https://github.com/webpack-contrib/sass-loader/issues/804 webpackImporter: false, }, }, }, }; ``` -------------------------------- ### Using when helper in craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/getting-started.md Demonstrates how to use the `when` helper function to conditionally configure ESLint and Webpack plugins based on environment variables. ```javascript module.exports = { eslint: { mode: 'file', configure: { formatter: when( process.env.NODE_ENV === 'CI', require('eslint-formatter-vso') ), }, }, webpack: { plugins: [ new ConfigWebpackPlugin(), ...whenDev(() => [new CircularDependencyPlugin()], []), ], }, }; ``` -------------------------------- ### Add New Webpack Plugins Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-plugins.md Add new Webpack plugins to the configuration using `addPlugins`. Plugins can be appended or prepended to the existing list. ```js const { addPlugins } = require('@craco/craco'); const myNewWebpackPlugin = require.resolve('ESLintWebpackPlugin'); addPlugins(webpackConfig, [myNewWebpackPlugin]); addPlugins(webpackConfig, [[myNewWebpackPlugin, 'append']]); addPlugins(webpackConfig, [[myNewWebpackPlugin, 'prepend']]); ``` -------------------------------- ### Webpack Configuration with Object Literal Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/getting-started.md Example of overriding webpack configuration using an object literal in craco.config.js. This merges the provided configuration with the original CRA settings. ```javascript module.exports = { webpack: { configure: { entry: './path/to/my/entry/file.js', }, }, }; ``` -------------------------------- ### Exporting Craco Configuration as a Function Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/getting-started.md Shows how to export Craco configuration by returning an object from a function. The function receives environment variables as an argument. ```javascript module.exports = function ({ env }) { return { ... }; }; ``` -------------------------------- ### Exporting Craco Configuration as an Async Function Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/getting-started.md Illustrates exporting Craco configuration using an async function, allowing for asynchronous operations before returning the configuration object. ```javascript module.exports = async function ({ env }) { await ...; return { ... }; }; ``` -------------------------------- ### Add Loader Before All Matching Loaders Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-loaders.md Use `addBeforeLoaders` to insert a new loader before all loaders that match the provided criteria. ```javascript const { addBeforeLoaders, loaderByName } = require('@craco/craco'); const myNewWebpackLoader = { loader: require.resolve('tslint-loader'), }; addBeforeLoaders( webpackConfig, loaderByName('eslint-loader'), myNewWebpackLoader ); ``` -------------------------------- ### Import throwUnexpectedConfigError Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/miscellaneous.md Import the `throwUnexpectedConfigError` function from the `@craco/craco` package. ```javascript const { throwUnexpectedConfigError } = require('@craco/craco'); ``` -------------------------------- ### Configure markdown-loader in craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-markdown-loader.md This snippet shows how to add markdown-loader to your Craco webpack configuration. It imports Markdown files as HTML and requires `html-loader` and `markdown-loader`. Ensure you have installed these dependencies. ```javascript const { addBeforeLoader, loaderByName } = require('@craco/craco'); module.exports = { webpack: { configure: (webpackConfig) => { webpackConfig.resolve.extensions.push('.md'); const markdownLoader = { test: /\.md$/, exclude: /node_modules/, use: [ { loader: require.resolve('html-loader'), }, { loader: require.resolve('markdown-loader'), options: { // see }, }, ], }; addBeforeLoader( webpackConfig, loaderByName('file-loader'), markdownLoader ); return webpackConfig; }, }, }; ``` -------------------------------- ### Basic Webpack Configuration Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/webpack.md This snippet shows the basic structure for configuring Webpack within craco.config.js, including options for aliases, plugins, and general configuration. ```javascript module.exports = { // ... webpack: { alias: { /* ... */ }, plugins: { add: [ /* ... */ ], remove: [ /* ... */ ], }, configure: { /* ... */}, configure: (webpackConfig, { env, paths }) => { /* ... */ return webpackConfig; }, }, }; ``` -------------------------------- ### Define ESLint configuration in .eslintrc.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-an-eslint-config-file.md Specify your ESLint configuration, such as extending from 'eslint-config-react-app', in your `.eslintrc.js` file. ```javascript module.exports = { extends: ['eslint-config-react-app'], }; ``` -------------------------------- ### Add Loader Before a Specific Loader Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-loaders.md Use `addBeforeLoader` to insert a new loader immediately before a target loader identified by a matcher. ```javascript const { addBeforeLoader, loaderByName } = require('@craco/craco'); const myNewWebpackLoader = { loader: require.resolve('tslint-loader'), }; addBeforeLoader( webpackConfig, loaderByName('eslint-loader'), myNewWebpackLoader ); ``` -------------------------------- ### Customize CRACO Config with overrideCracoConfig Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/hooks.md Use the overrideCracoConfig hook to modify the CRACO configuration object before it's processed. This example logs plugin options and the existing cracoConfig. Ensure the hook returns the modified cracoConfig. ```javascript module.exports = { overrideCracoConfig: ({ cracoConfig, pluginOptions, context: { env, paths }, }) => { if (pluginOptions.preText) { console.log(pluginOptions.preText); } console.log(JSON.stringify(cracoConfig, null, 4)); return cracoConfig; }, }; ``` ```javascript const logPlugin = require('./craco-log-plugin'); module.exports = { // ... plugins: [ { plugin: logPlugin, options: { preText: 'CRACO CONFIG' }, }, ], }; ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/dilanx/craco/blob/main/website/docs/getting-started.md Activate verbose logging for CRACO by specifying the --verbose CLI option in your package.json scripts. ```json { "scripts": { "start": "craco start --verbose" } } ``` -------------------------------- ### Add Asset Module Before Matching Module Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Inserts a new asset module directly before the first matching asset module found by the matcher. Ensures specific ordering. ```javascript const { addBeforeAssetModule, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addBeforeAssetModule( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` -------------------------------- ### craco.config.js Configuration for ts-loader Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-ts-loader.md This configuration replaces the default babel-loader with ts-loader for application code, enabling `transpileOnly: true` for faster builds. It also ensures that babel-loader is still used for non-application JavaScript files. Ensure `ts-loader` is installed as a dependency. ```javascript const { addAfterLoader, removeLoaders, loaderByName, getLoaders, throwUnexpectedConfigError, } = require('@craco/craco'); const throwError = (message) => throwUnexpectedConfigError({ packageName: 'craco', githubRepo: 'gsoft-inc/craco', message, githubIssueQuery: 'webpack', }); module.exports = { webpack: { configure: (webpackConfig, { paths }) => { const { hasFoundAny, matches } = getLoaders( webpackConfig, loaderByName('babel-loader') ); if (!hasFoundAny) throwError('failed to find babel-loader'); console.log('removing babel-loader'); const { hasRemovedAny, removedCount } = removeLoaders( webpackConfig, loaderByName('babel-loader') ); if (!hasRemovedAny) throwError('no babel-loader to remove'); if (removedCount !== 2) throwError('had expected to remove 2 babel loader instances'); console.log('adding ts-loader'); const tsLoader = { test: /\.(js|mjs|jsx|ts|tsx)$/, include: paths.appSrc, loader: require.resolve('ts-loader'), options: { transpileOnly: true }, }; const { isAdded: tsLoaderIsAdded } = addAfterLoader( webpackConfig, loaderByName('url-loader'), tsLoader ); if (!tsLoaderIsAdded) throwError('failed to add ts-loader'); console.log('added ts-loader'); console.log('adding non-application JS babel-loader back'); const { isAdded: babelLoaderIsAdded } = addAfterLoader( webpackConfig, loaderByName('ts-loader'), matches[1].loader // babel-loader ); if (!babelLoaderIsAdded) throwError('failed to add back babel-loader for non-application JS'); console.log('added non-application JS babel-loader back'); return webpackConfig; }, }, }; ``` -------------------------------- ### Add Loader After All Matching Loaders Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-loaders.md Use `addAfterLoaders` to insert a new loader after all loaders that match the provided criteria. ```javascript const { addAfterLoaders, loaderByName } = require('@craco/craco'); const myNewWebpackLoader = { loader: require.resolve('tslint-loader'), }; addAfterLoaders( webpackConfig, loaderByName('eslint-loader'), myNewWebpackLoader ); ``` -------------------------------- ### Add Asset Module Before All Matching Modules Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Inserts a new asset module before all asset modules that match the provided criteria. Useful for applying a rule to multiple existing modules. ```javascript const { addBeforeAssetModules, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addBeforeAssetModules( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` -------------------------------- ### Customize Jest Configuration with overrideJestConfig Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/hooks.md Use `overrideJestConfig` to modify the Jest configuration. This hook receives the current Jest config, Craco config, plugin options, and context. It must return a valid Jest config object. The example logs provided plugin options and the existing Jest config before returning it. ```javascript module.exports = { overrideJestConfig: ({ jestConfig, cracoConfig, pluginOptions, context: { env, paths, resolve, rootDir }, }) => { if (pluginOptions.preText) { console.log(pluginOptions.preText); } console.log(JSON.stringify(jestConfig, null, 4)); return jestConfig; }, }; ``` ```javascript const logPlugin = require('./craco-log-plugin'); module.exports = { // ... plugins: [ { plugin: logPlugin, options: { preText: 'JEST CONFIG' }, }, ], }; ``` -------------------------------- ### addBeforeAssetModules Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Adds a new asset module before all asset modules in the Webpack configuration that match the provided matcher function. Returns the number of modules added and a success indicator. ```APIDOC ## addBeforeAssetModules `addBeforeAssetModules(webpackConfig: WebpackConfig, matcher: AssetModuleMatcher, newAssetModule: Rule)` Add a new asset module **before all** of the asset modules for which the matcher returns true in the Webpack config. #### Return Type ```json { "isAdded": boolean; "addedCount": number; } ``` #### Usage ```js const { addBeforeAssetModules, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addBeforeAssetModules( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` ``` -------------------------------- ### createWebpackProdConfig Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration-api.md Generates a Webpack production configuration object. It accepts a CRACO config, an optional context, and an options object. Note that it does not accept the CRACO config as a function. ```APIDOC ## createWebpackProdConfig ### Description Generates a Webpack production configuration object based on the provided CRACO configuration. ### Method Signature `createWebpackProdConfig(cracoConfig, context = {}, options = { verbose: false, config: null })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **cracoConfig**: An object representing the CRACO configuration. * **context**: An optional context object. Defaults to an empty object. * **options**: An optional object with configuration options. * **verbose**: (boolean) - Optional - If true, enables verbose logging. Defaults to false. * **config**: (string) - Optional - Path to a specific configuration file. Defaults to null. ### Request Example ```javascript const { createWebpackProdConfig } = require('@craco/craco'); const cracoConfig = require('./craco.config.js'); const webpackConfig = createWebpackProdConfig(cracoConfig); module.exports = webpackConfig; ``` ### Response #### Success Response * **webpackConfig** (object) - The generated Webpack production configuration object. #### Response Example ```json { "webpackConfig": { ... } } ``` ``` -------------------------------- ### Craco Jest Configuration Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-a-jest-config-file.md This snippet shows how to configure Jest within your `craco.config.js` file. It defines global configuration options for Jest. ```javascript module.exports = { jest: { configure: { globals: { CONFIG: true, }, }, }, }; ``` -------------------------------- ### getAssetModule Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Retrieves the first asset module from the Webpack configuration for which the provided matcher function returns true. It returns whether a match was found and details of the match. ```APIDOC ## getAssetModule `getAssetModule(webpackConfig: WebpackConfig, matcher: AssetModuleMatcher)` Retrieve the **first** asset module for which the matcher returns true from the Webpack config. #### Return Type ```json { "isFound": boolean; "match": { "rule": Rule; "index": number; } } ``` #### Usage ```js const { getAssetModule, assetModuleByName } = require('@craco/craco'); const { isFound, match } = getAssetModule( webpackConfig, assetModuleByName('asset/source') ); if (isFound) { // do stuff... } ``` ``` -------------------------------- ### getAssetModules Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Retrieves all asset modules from the Webpack configuration for which the provided matcher function returns true. It indicates if any matches were found and provides a list of all matches. ```APIDOC ## getAssetModules `getAssetModules(webpackConfig: WebpackConfig, matcher: AssetModuleMatcher)` Retrieve **all** of the asset modules for which the matcher returns true from the Webpack config. #### Return Type ```json { "hasFoundAny": boolean; "matches": [ { "rule": Rule; "index": number; } ] } ``` #### Usage ```js const { getAssetModules, assetModuleByName } = require('@craco/craco'); const { hasFoundAny, matches } = getAssetModules( webpackConfig, assetModuleByName('asset/inline') ); if (hasFoundAny) { matches.forEach((x) => { // do stuff... }); } ``` ``` -------------------------------- ### createJestConfig Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration-api.md Generates a Jest configuration object. It accepts a CRACO config, an optional Jest context object, and an options object. Note that it does not accept the CRACO config as a function. ```APIDOC ## createJestConfig ### Description Generates a Jest configuration object based on the provided CRACO configuration. ### Method Signature `createJestConfig(cracoConfig, context = {}, options = { verbose: false, config: null })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **cracoConfig**: An object representing the CRACO configuration. * **context**: An optional Jest context object. Defaults to an empty object. * **options**: An optional object with configuration options. * **verbose**: (boolean) - Optional - If true, enables verbose logging. Defaults to false. * **config**: (string) - Optional - Path to a specific configuration file. Defaults to null. ### Request Example ```javascript const { createJestConfig } = require('@craco/craco'); const cracoConfig = require('./craco.config.js'); const jestConfig = createJestConfig(cracoConfig); module.exports = jestConfig; ``` ### Response #### Success Response * **jestConfig** (object) - The generated Jest configuration object. #### Response Example ```json { "jestConfig": { ... } } ``` ``` -------------------------------- ### addBeforeAssetModule Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Adds a new asset module to the Webpack configuration immediately before the first asset module that matches the provided matcher function. Returns a boolean indicating if the addition was successful. ```APIDOC ## addBeforeAssetModule `addBeforeAssetModule(webpackConfig: WebpackConfig, matcher: AssetModuleMatcher, newAssetModule: Rule)` Add a new asset module **before** the asset module for which the matcher returns true in the Webpack config. #### Return Type ```json { "isAdded": boolean; } ``` #### Usage ```js const { addBeforeAssetModule, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addBeforeAssetModule( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` ``` -------------------------------- ### Add Asset Module After Matching Module Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Inserts a new asset module directly after the first matching asset module found by the matcher. Useful for maintaining a specific order. ```javascript const { addAfterAssetModule, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addAfterAssetModule( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` -------------------------------- ### addAfterAssetModule Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Adds a new asset module to the Webpack configuration immediately after the first asset module that matches the provided matcher function. Returns a boolean indicating if the addition was successful. ```APIDOC ## addAfterAssetModule `addAfterAssetModule(webpackConfig: WebpackConfig, matcher: AssetModuleMatcher, newAssetModule: Rule)` Add a new asset module **after** the asset module for which the matcher returns true in the Webpack config. #### Return Type ```json { "isAdded": boolean; } ``` #### Usage ```js const { addAfterAssetModule, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addAfterAssetModule( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` ``` -------------------------------- ### Configure Stylelint Plugin in craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/add-stylelint.md Add the StylelintWebpackPlugin to your craco.config.js file to enable CSS linting. This configuration specifies the context and files to lint. ```javascript const path = require('path'); const StyleLintPlugin = require('stylelint-webpack-plugin'); module.exports = { webpack: { plugins: { add: [ new StyleLintPlugin({ configBasedir: __dirname, context: path.resolve(__dirname, 'src'), files: ['**/*.css'], }), ], }, }, }; ``` -------------------------------- ### Add Asset Module After All Matching Modules Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Inserts a new asset module after all asset modules that match the provided criteria. Useful for applying a rule to multiple existing modules while maintaining order. ```javascript const { addAfterAssetModules, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addAfterAssetModules( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` -------------------------------- ### addPlugins Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-plugins.md Adds new Webpack plugins to the configuration. You can specify whether to append or prepend the plugins, using the same syntax as defined in the Craco configuration. ```APIDOC ## addPlugins ### Description Add new plugins to the Webpack config. Plugins are added with the [same syntax used within the CRACO config](../../configuration/webpack.md#webpackpluginsadd). ### Signature `addPlugins(webpackConfig: WebpackConfig, plugins: [WebpackPlugin | [WebpackPlugin, 'append' | 'prepend']]): void` ### Usage ```js const { addPlugins } = require('@craco/craco'); const myNewWebpackPlugin = require.resolve('ESLintWebpackPlugin'); addPlugins(webpackConfig, [myNewWebpackPlugin]); addPlugins(webpackConfig, [[myNewWebpackPlugin, 'append']]); addPlugins(webpackConfig, [[myNewWebpackPlugin, 'prepend']]); ``` ``` -------------------------------- ### craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/add-autoprefixer-options.md Configure Autoprefixer options by adding the `autoprefixer` object within the `postcss.env` configuration in `craco.config.js`. This allows you to customize Autoprefixer behavior, such as enabling the `cascade` option. ```javascript module.exports = { style: { postcss: { env: { autoprefixer: { cascade: true, }, }, }, }, }; ``` -------------------------------- ### Configure Babel for MobX Decorators Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-mobx.md Add the '@babel/plugin-proposal-decorators' plugin to your craco.config.js to enable MobX decorators. ```javascript module.exports = { babel: { plugins: [['@babel/plugin-proposal-decorators', { legacy: true }]], }, }; ``` -------------------------------- ### Add Loader After a Specific Loader Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-loaders.md Use `addAfterLoader` to insert a new loader immediately after a target loader identified by a matcher. ```javascript const { addAfterLoader, loaderByName } = require('@craco/craco'); const myNewWebpackLoader = { loader: require.resolve('tslint-loader'), }; addAfterLoader( webpackConfig, loaderByName('eslint-loader'), myNewWebpackLoader ); ``` -------------------------------- ### getPlugin Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-plugins.md Retrieves the first Webpack plugin from a given Webpack configuration that matches a provided plugin matcher. It returns an object indicating if a plugin was found and the matched plugin itself. ```APIDOC ## getPlugin ### Description Retrieve the **first** plugin for which the matcher returns true from the Webpack config. ### Signature `getPlugin(webpackConfig: WebpackConfig, matcher: PluginMatcher)` ### Return Type ```json { "isFound": boolean; "match": WebpackPlugin; } ``` ### Usage ```js const { getPlugin, pluginByName } = require('@craco/craco'); const { isFound, match } = getPlugin( webpackConfig, pluginByName('ESLintWebpackPlugin') ); if (isFound) { // do stuff... } ``` ``` -------------------------------- ### overrideDevServerConfig Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/hooks.md Allows plugins to override the development server configuration. It receives the current dev server configuration and other contextual data, and must return a valid DevServer config object. ```APIDOC ## overrideDevServerConfig ### Description This hook allows plugins to modify the development server configuration before it is used by Craco. It provides access to the existing configuration, the Craco configuration, plugin options, and a context object. ### Signature `overrideDevServerConfig(data): DevServerConfig` ### Parameters #### `data` (object) - Required An object containing the following properties: - **`devServerConfig`** (object) - The [DevServer config](https://webpack.js.org/configuration/dev-server/#devserver) object already customized by CRACO. - **`cracoConfig`** (object) - The config object read from the [CRACO config](../configuration/getting-started.md) provided by the consumer. - **`pluginOptions`** (object) - The plugin options provided by the consumer. - **`context`** (object) - A [context object](../configuration/getting-started.md#context-object--env-paths-) ([DevServer-specific](../configuration/devserver.md#devserver-1)) containing `env`, `paths`, and `allowedHost`. ### Returns - **`DevServerConfig`** (object) - A valid [DevServer config](https://webpack.org/configuration/dev-server/#devserver) object. ### Example ```javascript module.exports = { overrideDevServerConfig: ({ devServerConfig, cracoConfig, pluginOptions, context: { env, paths, allowedHost } }) => { if (pluginOptions.preText) { console.log(pluginOptions.preText); } console.log(JSON.stringify(devServerConfig, null, 4)); return devServerConfig; }, }; ``` ``` -------------------------------- ### addBeforeLoader Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-loaders.md Adds a new Webpack loader to the configuration immediately before the first loader that matches the provided loader matcher function. Returns a boolean indicating if the loader was successfully added. ```APIDOC ## addBeforeLoader ### Description Add a new loader **before** the loader for which the matcher returns true in the Webpack config. ### Signature `addBeforeLoader(webpackConfig: WebpackConfig, matcher: LoaderMatcher, newLoader: Rule)` ### Return Type ```json { "isAdded": boolean; } ``` ### Usage ```javascript const { addBeforeLoader, loaderByName } = require('@craco/craco'); const myNewWebpackLoader = { loader: require.resolve('tslint-loader'), }; addBeforeLoader( webpackConfig, loaderByName('eslint-loader'), myNewWebpackLoader ); ``` ``` -------------------------------- ### craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-preact.md Configure Craco to use the craco-preact plugin. This file should be placed at the root of your project. ```javascript // Official documentation available at: https://github.com/FormAPI/craco-preact module.exports = { plugins: [{ plugin: require('craco-preact') }], }; ``` -------------------------------- ### Craco Jest Configuration Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/jest.md Configure Jest settings, including Babel presets and plugins, or provide a custom Jest configuration object or function. Use an object literal for simple settings or a function for more complex, dynamic configurations. ```javascript module.exports = { // ... jest: { babel: { addPresets: true /* (default value) */, addPlugins: true /* (default value) */, }, configure: { /* ... */ }, configure: (jestConfig, { env, paths, resolve, rootDir }) => { /* ... */ return jestConfig; }, }, }; ``` -------------------------------- ### craco.config.js Configuration for less-loader Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-less-loader.md Configure Craco to use the craco-less plugin. Ensure no IE compatibility is enabled. ```javascript module.exports = { plugins: [ { plugin: require('craco-less'), options: { noIeCompat: true, }, }, ], }; ``` -------------------------------- ### addAfterAssetModules Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-asset-modules.md Adds a new asset module after all asset modules in the Webpack configuration that match the provided matcher function. Returns the number of modules added and a success indicator. ```APIDOC ## addAfterAssetModules `addAfterAssetModules(webpackConfig: WebpackConfig, matcher: AssetModuleMatcher, newAssetModule: Rule)` Add a new asset module **after all** of the asset modules for which the matcher returns true in the Webpack config. #### Return Type ```json { "isAdded": boolean; "addedCount": number; } ``` #### Usage ```js const { addAfterAssetModules, assetModuleByName } = require('@craco/craco'); const myNewWebpackAssetModule = { test: /\.png/, type: 'asset/resource', }; addAfterAssetModules( webpackConfig, assetModuleByName('asset/source'), myNewWebpackAssetModule ); ``` ``` -------------------------------- ### Include Third-Party CRACO Plugins Source: https://github.com/dilanx/craco/blob/main/website/docs/configuration/plugins.md Configure CRACO to use external plugins by listing them in the `plugins` array within `craco.config.js`. Each plugin can have its own options object for customization. ```javascript module.exports = { // ... plugins: [ { plugin: require('some-craco-plugin'), options: { /* ... */ }, }, // ... ], }; ``` -------------------------------- ### craco.config.js Source: https://github.com/dilanx/craco/blob/main/website/recipes/use-an-https-dev-server.md Configure Craco to enable HTTPS for the development server. This requires specifying the path to a PFX certificate file and its passphrase. ```javascript const path = require('path'); const fs = require('fs'); const { whenDev } = require('@craco/craco'); module.exports = { devServer: whenDev(() => ({ https: true, pfx: fs.readFileSync(path.resolve('./localhost.pfx')), pfxPassphrase: 'temp123!', })), }; ``` -------------------------------- ### Import Craco Plugin Utilities Source: https://github.com/dilanx/craco/blob/main/website/docs/plugin-api/utility-functions/webpack-plugins.md Import necessary utility functions for Webpack plugin management from the '@craco/craco' package. ```js const { pluginByName, getPlugin, addPlugins, removePlugins, } = require('@craco/craco'); ```