Сбой анализа React Module: неожиданный символ '@' - PullRequest
0 голосов
/ 20 декабря 2018

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

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

Я использую этот модуль: https://fonticonpicker.github.io/react-fonticonpicker/

Я получаю эту ошибку:

./node_modules/@fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css Сбой при синтаксическом анализе модуля: неожиданный символ '@' (18: 0) Вам может потребоваться соответствующий загрузчикобрабатывать этот тип файла.|* | / |@ font-face {font-family: fontIconPicker; src: url (assets / fontIconPicker.ttf) формат ("truetype"), url (assets / fontIconPicker.woff) формат ("woff"), url (assets / fontIconPicker.svg#fontIconPicker) format ("svg"); font-weight: 400; font-style: normal} [class = "fipicon -"], [class ^ = fipicon -] {font-family: fontIconPicker! важный;говорить: нет; стиль шрифта .......

Ошибка может быть воспроизведена с моим кодом из github: https://github.com/gregbia/my-app

Используйте npm install и npm start и отобразится ошибка.

Мой веб-пакет выглядит так:

/**
 * 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.
    },
};

Ответы [ 4 ]

0 голосов
/ 26 декабря 2018

На самом деле, я так удивлен, что вы использовали SCSS конфигурации веб-пакетов рядом с PostCSS, потому что с небольшой конфигурацией вы можете предварительно обработать свои CSS файлы и затем обработать ихв сжатую версию по синтаксису SCSS.Я установил вам конфиг в по этой ссылке .Я знаю, что это не ваша основная проблема, но я думаю, что конфигурация вашего проекта не оптимизирована.

Приведенная выше ссылка на конфигурацию webpack поможет вам улучшить вашу конфигурацию и вы сможете увидеть конфигурации веб-пакетов шрифтов.В любом случае ...

Для вашей точной ошибки вы должны исправить конфигурацию шрифта в веб-пакете, как показано ниже:

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

Обновление после работы на репо :

Я пишу webpack.config.dev.js файл, как показано ниже:

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,
};

А также установить css-loader и file-loader.

npm install file-loader css-loader

Подсказка : кажется, что шрифты должны иметь outputPath в конфигурации веб-пакета.

0 голосов
/ 22 декабря 2018

Похоже, вы пропустили css-loader для .css, хранящегося в node_modules.Вот почему вы сталкиваетесь с этой проблемой .Запустите npm i -D css-loader и добавьте это правило в ваш node_modules > cgb-scrips > config > webpack.config.<env>.js файл:

module: {
  rules: [
    // ...

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

    // ...
  ],
},

В качестве альтернативы, чтобы пропустить редактирование webpack.config.js, вы можете просто импортировать ваши файлы так:

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';
0 голосов
/ 23 декабря 2018

Проблема в том, что webpack не загружает ваши шрифты @font-face в node_modules.Вы исключаете загрузку CSS из node_modules.Но ваш @fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css находится в node_modules.

Измените этот фрагмент в конфигурации вашего веб-пакета

{
  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']
}
0 голосов
/ 20 декабря 2018

Ваша конфигурация загрузчика в веб-пакете не соответствует CSS-файлу Route.

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

Это не style.css или editor.css.Следовательно вы получаете ошибку.Также вы игнорируете node_modules в вашей конфигурации загрузчика webpack, но вы импортируете css из node_modules.

Добавление

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

должно работать

...