React 模块解析失败:意外字符 '@'。

10
我在尝试在我的React组件中导入以下内容时遇到了错误:
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) 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;speak:none;font-style .......

您可以使用我的github代码重现此错误:https://github.com/gregbia/my-app

使用npm installnpm start,将会显示错误。

我的webpack配置如下:

/**
 * 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个回答

6

实际上,我很惊讶你在PostCSS旁边使用了SCSS webpack配置,因为通过一些配置,你可以对CSS进行预处理,然后使用SCSS语法将其后处理为压缩版本。我在此链接中为你设置了一个配置。我知道这不是你的主要问题,但我认为你的项目配置还不够优化。

上面的webpack配置链接将帮助你改进你的配置,并且你可以查看字体的webpack配置。无论如何...

针对你的具体错误,你应该像下面这样修复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-loaderfile-loader
npm install file-loader css-loader

提示:看起来字体需要在webpack配置中有一个outputPath


4
问题是webpack没有加载你在node_modules中的字体@font-face。你正在排除从node_modules加载css。但是你的@fonticonpicker/react-fonticonpicker/dist/fonticonpicker.base-theme.react.css在node_modules中。
请更改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']
}

3
似乎你缺少存储在node_modules中的.css文件所需的css-loader。这就是为什么你会遇到这个问题的原因。运行npm i -D css-loader并将此规则添加到你的node_modules > cgb-scrips > config > webpack.config..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';

2

您在webpack中的loader配置与CSS文件路由不匹配。

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

这不是 style.csseditor.css。因此您会收到错误。另外,您在webpack加载器配置中忽略了node_modules,但您从node_modules导入css。

添加

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

应该可以正常工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接