简体   繁体   English

无法使用 webpack 5 在 React 中加载 JSON 文件

[英]Cannot load JSON files in React with webpack 5

Summarize the problem总结问题

I created a webpack react boilerplate for my projects and it works fine except it cannot handle JSON files and according to webpack documentation:我为我的项目创建了一个 webpack react 样板文件,它工作正常,除了它不能处理 JSON 文件并根据 webpack 文档:

⚠️ Since webpack >= v2.0.0, importing of JSON files will work by default. ⚠️ 由于 webpack >= v2.0.0,JSON 文件的导入将默认工作。 You might still want to use this if you use a custom file extension.如果您使用自定义文件扩展名,您可能仍想使用它。 See the v1.0.0 -> v2.0.0 Migration Guide for more information有关详细信息,请参阅 v1.0.0 -> v2.0.0 迁移指南

Describe what you've tried描述你尝试过的东西

Here's my webpack common setup:这是我的 webpack 常用设置:

const path = require('path'),
//used to check if the given file exists
fs = require('fs'),
//dotenv
dotenv = require('dotenv'),
//plugins
{ DefinePlugin } = require('webpack'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
MiniCssExtractPlugin = require('mini-css-extract-plugin'),
EsLintPlugin = require('eslint-webpack-plugin'),
//constants
{
    port,
    devServer,
    jsSubDirectory,
    isCssModules,
    metaInfo: { title, description, url, keywords },
} = require('./constants'),
PATHS = require('./paths'),
fullDevServerUrl = `${devServer}:${port}`;

module.exports = (env, options) => {
    // the mode variable is passed in package.json scripts (development, production)
    const isDevelopment = options.mode === 'development',
        /*================ setup environments variables ===================*/
        // create a fallback path (the production .env)
        basePath = `${PATHS.environments}/.env`,
        // concatenate the environment name to the base path to specify the correct env file!
        envPath = `${basePath}.${options.mode}`,
        // check if the file exists, otherwise fall back to the production .env
        finalPath = fs.existsSync(envPath) ? envPath : basePath,
        // set the path parameter in the dotenv config
        fileEnv = dotenv.config({ path: finalPath }).parsed,
        // create an object from the current env file with all keys
        envKeys = Object.keys(fileEnv).reduce((prev, next) => {
            prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
            return prev;
        }, {});
    /*================ finish setup environments variables ===================*/

return {
    entry: `${PATHS.src}/index.js`,
    output: {
        // __dirname is the absolute path to the root directory of our app
        path: PATHS.outputSrc,
        // hashes are very important in production for caching purposes
        filename: jsSubDirectory + 'bundle.[contenthash:8].js',
        // used for the lazy loaded component
        chunkFilename: jsSubDirectory + '[name].[contenthash:8].js',
        publicPath: '/',
        assetModuleFilename: (pathData) => {
            //allows us to have the same folder structure of assets as we have it in /src
            const filepath = path.dirname(pathData.filename).split('/').slice(1).join('/');
            return `${filepath}/[name].[hash][ext][query]`;
        },
    },
    optimization: {
        // used to avoid duplicated dependencies from node modules
        runtimeChunk: 'single',
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendor',
                    enforce: true,
                    chunks: 'all',
                },
            },
        },
    },
    resolve: {
        extensions: ['.js', '.jsx', '.json'],
        // declaring alias for reducing the use of relative path
        alias: {
            '@/js': `${PATHS.src}/js`,
            '@/scss': `${PATHS.src}/scss`,
            '@/img': `${PATHS.src}/assets/images`,
            '@/jest': PATHS.jest,
        },
    },
    module: {
        rules: [
            {
                test: /\.js|jsx$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: { cacheDirectory: true },
                },
            },
            {
                test: /\.(jpe?g|svg|png|gif|ico|eot|ttf|woff2?)(\?v=\d+\.\d+\.\d+)?$/i,
                type: 'asset/resource',
            },
            {
                test: /\.s?[ac]ss$/,
                //removed (exclude: /node_modules/) to enable using external styles
                use: [
                    {
                        // style-loader => insert styles in the head of the HTML as style tags or in blob links
                        // MiniCssExtractPlugin => extract styles to a file
                        loader: isDevelopment ? 'style-loader' : MiniCssExtractPlugin.loader,
                        //if source map is set to true from previous loaders => this loader will be true as well
                    },
                    {
                        //Resolves @import statements
                        loader: 'css-loader',
                        options: {
                            // used for debugging the app (to see from which component styles are applied)
                            sourceMap: isDevelopment,
                            // Number of loaders applied before CSS loader (which is postcss-loader)
                            importLoaders: 3,
                            // the following is used to enable CSS modules
                            ...(isCssModules
                                ? {
                                        modules: {
                                            //exclude external styles from css modules transformation
                                            auto: (resourcePath) => !resourcePath.includes('node_modules'),
                                            mode: (resourcePath) => {
                                                if (/global.scss$/i.test(resourcePath)) {
                                                    return 'global';
                                                }

                                                return 'local';
                                            },
                                            localIdentName: isDevelopment ? '[name]_[local]' : '[contenthash:base64]',
                                            localIdentContext: PATHS.src,
                                            localIdentHashSalt: 'react-boilerplate',
                                            exportLocalsConvention: 'camelCaseOnly',
                                        },
                                  }
                                : {}),
                        },
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                ident: 'postcss',
                                plugins: [
                                    'postcss-flexbugs-fixes',
                                    [
                                        'postcss-preset-env',
                                        {
                                            autoprefixer: {
                                                flexbox: 'no-2009',
                                            },
                                            stage: 3,
                                        },
                                    ],
                                    // Adds PostCSS Normalize as the reset css with default options,
                                    // so that it honors browserslist config in package.json
                                    // which in turn let's users customize the target behavior as per their needs.
                                    'postcss-normalize',
                                ],
                            },
                            sourceMap: isDevelopment,
                        },
                    },
                    {
                        //Rewrites relative paths in url() statements based on the original source file
                        loader: 'resolve-url-loader',
                        options: {
                            //needs sourcemaps to resolve urls (images)
                            sourceMap: true,
                        },
                    },
                    {
                        //Compiles Sass to CSS
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true,
                        },
                    },
                ],
            },
        ],
    },
    plugins: [
        new EsLintPlugin({
            extensions: ['.js', '.jsx', '.json'],
        }),
        new HtmlWebpackPlugin({
            title,
            template: `${PATHS.src}/index.html`,
            filename: 'index.html',
            inject: 'body',
            favicon: `${PATHS.src}/assets/images/favicon.png`,
            meta: {
                description,
                keywords,
                url: isDevelopment ? fullDevServerUrl : url,
                'apple-mobile-web-app-capable': 'yes',
                'mobile-web-app-capable': 'yes',
            },
        }),
        new DefinePlugin(envKeys),
    ],
};

}; };

Here's the link of the repository: https://github.com/react-custom-projects/webpack-react-boilerplate这是存储库的链接: https://github.com/react-custom-projects/webpack-react-boilerplate

Fixed using the following steps:使用以下步骤修复:

webpack.common.js: webpack.common.js:

  • json files was going through babel-loader because my regular expression for js and jsx was wrong. json文件正在通过babel-loader ,因为我的jsjsx正则表达式是错误的。 This is the correct regular expression:这是正确的正则表达式:

    test: /\.(js|jsx)$/,

eslintrc.js: eslintrc.js:

  • ignore json files:忽略 json 文件:

    ignorePatterns: ['**/src/**/*.json'],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Webpack React:有条件地加载json配置文件 - Webpack React: Conditionally load json config files 无法使用 webpack 加载 png 文件,意外字符 - cannot load png files with webpack, unexpected character Webpack 加载器配置为 React JS 加载 css 和 sass 文件 - Webpack loader configuration to load css and sass files for React JS 尝试使用 file-loader 和 webpack 加载大型 json 文件 - Trying to load large json files using file-loader and webpack webpack无法加载图像 - webpack cannot load image 使用 webpack 加载 .jsx 文件 - Load .jsx files with webpack 使用webpack从主捆绑包中排除JSON文件以进行react-lottie - Exclude JSON files from the main bundle with webpack for react-lottie 使用带有 webpack 5 的图像文件并做出反应,webpack 正在处理图像但不会在浏览器中加载 - Using image files with webpack 5 and react, webpack is processing the image but it won't load in the browser 当使用babel,webpack和gulp作为构建工具时,有没有办法单独加载反应库文件而不是捆绑文件? - Is there a way to load react library files separately and not in the bundled files when using react with babel, webpack and gulp as building tool? 无法将图像加载到 Konva-React,出现 TypeError: react-konva webpack …图像不是构造函数 - Cannot get image to load into Konva-React, Getting TypeError: react-konva webpack …Image is not a constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM