web-dev-qa-db-fra.com

Echec de l'analyse du module React: caractère inattendu '@'

Je reçois une erreur lorsque j'essaie d'importer les éléments suivants dans mon composant de réaction:

import FontIconPicker from '@fonticonpicker/react-fonticonpicker';
import '@fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css';

J'utilise ce module: https://fonticonpicker.github.io/react-fonticonpicker/

Je reçois cette erreur:

./node_modules/@fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css Echec de l'analyse du module: Caractère inattendu '@' (18: 0) Vous aurez peut-être besoin d'un chargeur approprié pour gérer ce type de fichier. | * | / | @ font-face {font-family: fontIconPicker; src: url (assets/fontIconPicker.ttf) format ("truetype"), url (assets/fontIconPicker.woff) format ("woff"), url (assets/fontIconPicker.svg # fontIconPicker) format ("svg"); font-weight: 400; font-style: normal} [class = " fipicon -"], [class ^ = fipicon -] {font-family: fontIconPicker! important; parler : aucune; style de police .......

L'erreur peut être reproduite avec mon code de github: https://github.com/gregbia/my-app

Utilisez npm install et npm start et l'erreur s'affichera.

Mon webpack ressemble à ceci:

/**
 * Webpack Configuration
 *
 * Working of a Webpack can be very simple or complex. This is an intenally simple
 * build configuration.
 *
 * Webpack basics — If you are new the Webpack here's all you need to know:
 *     1. Webpack is a module bundler. It bundles different JS modules together.
 *     2. It needs and entry point and an ouput to process file(s) and bundle them.
 *     3. By default it only understands common JavaScript but you can make it
 *        understand other formats by way of adding a Webpack loader.
 *     4. In the file below you will find an entry point, an ouput, and a babel-loader
 *        that tests all .js files excluding the ones in node_modules to process the
 *        ESNext and make it compatible with older browsers i.e. it converts the
 *        ESNext (new standards of JavaScript) into old JavaScript through a loader
 *        by Babel.
 *
 * TODO: Instructions.
 *
 * @since 1.0.0
 */

const paths = require( './paths' );
const autoprefixer = require( 'autoprefixer' );
const ExtractTextPlugin = require( 'extract-text-webpack-plugin' );

// Extract style.css for both editor and frontend styles.
const blocksCSSPlugin = new ExtractTextPlugin( {
    filename: './dist/blocks.style.build.css',
} );

// Extract editor.css for editor styles.
const editBlocksCSSPlugin = new ExtractTextPlugin( {
    filename: './dist/blocks.editor.build.css',
} );

// Configuration for the ExtractTextPlugin — DRY rule.
const extractConfig = {
    use: [
        // "postcss" loader applies autoprefixer to our CSS.
        { loader: 'raw-loader' },
        {
            loader: 'postcss-loader',
            options: {
                ident: 'postcss',
                plugins: [
                    autoprefixer( {
                        browsers: [
                            '>1%',
                            'last 4 versions',
                            'Firefox ESR',
                            'not ie < 9', // React doesn't support IE8 anyway
                        ],
                        flexbox: 'no-2009',
                    } ),
                ],
            },
        },
        // "sass" loader converts SCSS to CSS.
        {
            loader: 'sass-loader',
            options: {
                // Add common CSS file for variables and mixins.
                data: '@import "./src/common.scss";\n',
                outputStyle: 'nested',
            },
        },
    ],
};

// Export configuration.
module.exports = {
    entry: {
        './dist/blocks.build': paths.pluginBlocksJs, // 'name' : 'path/file.ext'.
    },
    output: {
        // Add /* filename */ comments to generated require()s in the output.
        pathinfo: true,
        // The dist folder.
        path: paths.pluginDist,
        filename: '[name].js', // [name] = './dist/blocks.build' as defined above.
    },
    // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
    devtool: 'cheap-eval-source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx|mjs)$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        // @remove-on-eject-begin
                        babelrc: false,
                        presets: [ require.resolve( 'babel-preset-cgb' ) ],
                        // @remove-on-eject-end
                        // This is a feature of `babel-loader` for webpack (not Babel itself).
                        // It enables caching results in ./node_modules/.cache/babel-loader/
                        // directory for faster rebuilds.
                        cacheDirectory: true,
                    },
                },
            },
            {
                test: /style\.s?css$/,
                exclude: /(node_modules|bower_components)/,
                use: blocksCSSPlugin.extract( extractConfig ),
            },
            {
                test: /editor\.s?css$/,
                exclude: /(node_modules|bower_components)/,
                use: editBlocksCSSPlugin.extract( extractConfig ),
            },
        ],
    },
    // Add plugins.
    plugins: [ blocksCSSPlugin, editBlocksCSSPlugin ],
    stats: 'minimal',
    // stats: 'errors-only',
    // Add externals.
    externals: {
        react: 'React',
        'react-dom': 'ReactDOM',
        ga: 'ga', // Old Google Analytics.
        gtag: 'gtag', // New Google Analytics.
        jquery: 'jQuery', // import $ from 'jquery' // Use the WordPress version.
    },
};
7
CyberJunkie

En fait, je suis tellement surpris que vous ayez utilisé SCSS webpack config à côté de PostCSS car avec une petite configuration , vous pouvez prétraiter votre CSSes et ensuite le traiter en version compressée à l'aide de la syntaxe SCSS. Je vous ai mis une configuration dans ce lien . Je sais que ce n'est pas votre problème principal mais je pense que la configuration de votre projet n'est pas optimisée.

Le lien ci-dessus de Webpack Config vous aidera à améliorer votre configuration et vous pourrez voir les configurations de polices Webpack. en tous cas...

Pour votre erreur exacte, vous devriez corriger votre configuration de police sur Webpack comme ci-dessous:

{
  test: /\.(woff|woff2|eot|ttf|svg)$/,
  exclude: /node_modules/,
  loader: 'file-loader',
  options: {
    limit: 1024,
    name: '[name].[ext]',
    publicPath: 'dist/assets/',
    outputPath: 'dist/assets/'
  }
},

Update après le travail sur le repo } _:

J'écris le fichier webpack.config.dev.js comme ci-dessous:

const paths = require('./paths');
const externals = require('./externals');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// Extract style.css for both editor and frontend styles.
const blocksCSSPlugin = new ExtractTextPlugin({
    filename: './dist/blocks.style.build.css',
});

// Extract editor.css for editor styles.
const editBlocksCSSPlugin = new ExtractTextPlugin({
    filename: './dist/blocks.editor.build.css',
});

// Configuration for the ExtractTextPlugin — DRY rule.
const extractConfig = {
    fallback: 'style-loader',
    use: [
        // "postcss" loader applies autoprefixer to our CSS.
        {loader: 'css-loader'},
        {
            loader: 'postcss-loader',
            options: {
                ident: 'postcss',
                plugins: [
                    autoprefixer({
                        browsers: [
                            '>1%',
                            'last 4 versions',
                            'Firefox ESR',
                            'not ie < 9', // React doesn't support IE8 anyway
                        ],
                        flexbox: 'no-2009',
                    }),
                ],
            },
        },
        // "sass" loader converts SCSS to CSS.
        {
            loader: 'sass-loader',
            options: {
                // Add common CSS file for variables and mixins.
                data: '@import "./src/common.scss";\n',
                outputStyle: 'nested',
            },
        },
    ],
};

// Export configuration.
module.exports = {
    entry: {
        './dist/blocks.build': paths.pluginBlocksJs, // 'name' : 'path/file.ext'.
    },
    output: {
        // Add /* filename */ comments to generated require()s in the output.
        pathinfo: true,
        // The dist folder.
        path: paths.pluginDist,
        filename: '[name].js', // [name] = './dist/blocks.build' as defined above.
    },
    // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
    devtool: 'cheap-eval-source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx|mjs)$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        // @remove-on-eject-begin
                        babelrc: false,
                        presets: [require.resolve('babel-preset-cgb')],
                        // @remove-on-eject-end
                        // This is a feature of `babel-loader` for webpack (not Babel itself).
                        // It enables caching results in ./node_modules/.cache/babel-loader/
                        // directory for faster rebuilds.
                        cacheDirectory: true,
                    },
                },
            },
            {
                test: /style\.s?css$/,
                exclude: /(node_modules|bower_components)/,
                use: blocksCSSPlugin.extract(extractConfig),
            },
            {
                test: /editor\.s?css$/,
                exclude: /(node_modules|bower_components)/,
                use: editBlocksCSSPlugin.extract(extractConfig),
            },
            {
                test: /\.css$/,
                include: /(node_modules\/@fonticonpicker\/react-fonticonpicker\/dist)/,
                loaders: ['style-loader', 'css-loader']
            },
            {
                test: /\.(woff|woff2|eot|ttf|svg)$/,
                include: /(node_modules\/@fonticonpicker\/react-fonticonpicker\/dist)/,
                loader: 'file-loader',
                options: {
                    limit: 1024,
                    name: '[name].[ext]',
                    publicPath: 'dist/assets/',
                    outputPath: 'dist/assets/'
                }
            }
        ],
    },
    // Add plugins.
    plugins: [blocksCSSPlugin, editBlocksCSSPlugin],
    stats: 'minimal',
    // stats: 'errors-only',
    // Add externals.
    externals: externals,
};

Et installez également css-loader et file-loader.

npm install file-loader css-loader

Indice: il semble que les polices doivent avoir une outputPath dans la configuration du webpack.

3
AmerllicA

Le problème est que Webpack ne charge pas vos polices @font-face dans node_modules. Vous excluez le chargement de CSS à partir de node_modules. Mais votre @fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css est dans node_modules.

Changer cet extrait dans la configuration de votre webpack

{
  test: /style\.s?css$/,
  exclude: /(node_modules|bower_components)/,
  use: blocksCSSPlugin.extract( extractConfig ),
},
{
  test: /editor\.s?css$/,
  exclude: /(node_modules|bower_components)/,
  use: editBlocksCSSPlugin.extract( extractConfig ),
},

à

{
  test: /style\.s?css$/,
  use: blocksCSSPlugin.extract( extractConfig ),
},
{
  test: /editor\.s?css$/,
  use: editBlocksCSSPlugin.extract( extractConfig ),
},
{ test: /(\.css$)/, // you need to load all css imported from node_modules
  loaders: ['style-loader', 'css-loader', 'postcss-loader']
}
2
Dinesh Pandiyan

On dirait que vous manquez css-loader pour .css stocké dans node_modules. C’est pourquoi vous êtes confronté à ce problème . Exécutez npm i -D css-loader et ajoutez cette règle à votre fichier node_modules > cgb-scrips > config > webpack.config.<env>.js:

module: {
  rules: [
    // ...

    {
      test: /\.css$/,
      use: [
        { loader: 'raw-loader' },
        { loader: 'css-loader' },
      ]
    },

    // ...
  ],
},

Alternativement, pour ignorer l'édition webpack.config.js, vous pouvez simplement importer vos fichiers de la manière suivante:

import 'raw-loader!css-loader!@fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css';
import 'raw-loader!css-loader!@fonticonpicker/react-fonticonpicker/dist/fonticonpicker.material-theme.react.css';
1
streletss

Votre configuration de chargeur dans Webpack ne correspond pas au fichier CSS Route.

import '@fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css';

Ce n'est ni style.css ni editor.css. Par conséquent, vous obtenez une erreur. De plus, vous ignorez node_modules dans la configuration de votre chargeur de packs Web, mais vous importez le css à partir de node_modules. 

Ajouter 

  {
       test: /react\.s?css$/,
       use: [{
        loader: 'css-loader',
        options: {
          modules: true
        }
      }],
  },

devrait marcher

1
Shubham Khatri