简体   繁体   English

如何使用Webpack将供应商CSS文件捆绑到React应用程序中?

[英]How to bundle vendor CSS files into a React app with Webpack?

I have some 3rd party libs, like Mapbox GL, which are installed via npm and have some CSS files they rely on in their work. 我有一些第三方库,例如Mapbox GL,它们是通过npm安装的,并且在工作中有一些CSS文件。

As for Mapbox GL, there is mapbox-gl/dist/mapbox-gl.css in node_modules . 至于Mapbox GL,在mapbox-gl/dist/mapbox-gl.cssmapbox-gl/dist/mapbox-gl.css node_modules I have index.html which is used as the entry point for my React app and contains a link to a CSS file with some defaults. 我有index.html,它用作我的React应用程序的入口,并包含指向CSS文件的链接(具有一些默认设置)。

<link rel="stylesheet" href="/vendor/core.css">

All other CSS rules are provided by CSS modules, so I have a single CSS file in a React UI component folder and import it from the component like this: 所有其他CSS规则均由CSS模块提供,因此我在React UI组件文件夹中有一个CSS文件,并从组件中将其导入,如下所示:

import * as style from './MyComponent.css';

How do I import vendor CSS files, like Mapbox GL example above and make the rules from it apply to the app? 如何导入供应商CSS文件(如上面的Mapbox GL示例)并使其中的规则适用于应用程序?

  1. If your vendor css files are specific to a component, you can import them directly into your component, like this: 如果您的供应商css文件是特定于组件的,则可以将其直接导入到组件中,如下所示:

     // Component1.js import React from 'react'; ... import 'vendor/path/to/styles.css'; ... 
  2. If you want to import a general css file (such as normalize.css), you can import them into your top-level html view. 如果要导入常规的CSS文件(例如normalize.css),则可以将其导入顶级html视图。 I usually have a JSX file which is transpiled by webpack to index.html . 我通常有一个JSX文件,该文件由webpack转换为index.html So you can do this: 因此,您可以执行以下操作:

     // index.jsx (transpiled to index.html) <style dangerouslySetInnerHTML={{ __html: require('!css-loader!normalize.css/normalize.css'), }} /> 
  3. Or, if you have pure HTML, you can let webpack do it for you using the html-loader 或者,如果您使用的是纯HTML,则可以让Webpack使用html-loader为您完成此操作


For your reference, this is my webpack.config: 供您参考,这是我的webpack.config:

webpackConfig = {
  module: {
    rules = [
      {
        // excluding for node-modules
        test: /.css$/,
        exclude: path.resolve('./node_modules'),
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: true,
              camelCase: true,
              importLoaders: 1,
              localIdentName: '[path][name]__[local]--[hash:base64:5]',
            },
          },
          'postcss-custom-loader',
        ],
      },
      {
        // only for node-modules
        test: /.css$/,
        include: path.resolve('./node_modules'),
        use: ['style-loader', 'css-loader', 'postcss-custom-loader'],
      },
...
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM