首页 > 解决方案 > 如何使用 webpack 从 node_modules 导入 css

问题描述

我已经开始从现有工具包https://material-ui.com/store/items/devias-kit-pro/构建我的应用程序。我已将其更改为使用 webpack.config.js 似乎工作正常。但是,似乎没有导入来自 node_modules 的 css 文件。例如 index.js 文件以这种方式导入 css:

import 'react-perfect-scrollbar/dist/css/styles.css';

但没有应用css。我怀疑我的 webpack 配置有问题,如下所示:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const Dotenv = require('dotenv-webpack');

const SRC_DIR = path.join(__dirname, '/src');
const PUB_DIR = path.join(__dirname, '/public');
const DIST_DIR = path.join(__dirname, '/dist');


module.exports = {
entry: { main: `${SRC_DIR}/index.js` },
output: {
 path: DIST_DIR,
 chunkFilename: '[chunkhash].chunk.js',
 publicPath: '/'

},
resolve: {
 alias: {
   src: path.resolve(__dirname, 'src/')
 }
},
module: {
 rules: [
   {
     test: /\.js$/,
     exclude: /node_modules/,
     use: ['babel-loader', 'source-map-loader'],

   },
   {
     test: /\.(png|jpg)$/,
     use: {
       loader: 'url-loader',
     },
   },
   {
     test: /\.scss$/,
     use: [
       'style-loader',
       MiniCssExtractPlugin.loader,
       'css-loader',
       'sass-loader',
     ],
   },
   {
     test: /\.css$/,

     use: [
       { loader: 'style-loader' },
       {
         loader: 'css-loader',
         options: {
           modules: true
         },
       },
       { loader: 'sass-loader' }
     ]
   }
 ],
},
optimization: {
 splitChunks: {
   cacheGroups: {
     css: {
       test: /\.(css|sass|scss)$/,
       name: 'commons',
       chunks: 'all',
       minChunks: 2,
       enforce: true,
     },
   },
 },
},
plugins: [
 new CleanWebpackPlugin({
   cleanAfterEveryBuildPatterns: ['dist'],
 }),
 new MiniCssExtractPlugin({
   filename: 'style.[contenthash].css',
 }),
 new HtmlWebpackPlugin({
   inject: true,
   title: 'React-Redux-Webpack-Starter-Kit',
   template: `${PUB_DIR}/index.html`,
   filename: 'index.html',
   favicon: `${PUB_DIR}/favicon.ico`,
   meta: {
     viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no',
   },
 }),
 new WebpackMd5Hash(),
 new Dotenv(),
],
devtool: 'source-map',
devServer: {
 port: 3003,
 historyApiFallback: true,
 open: true,

 watchOptions: {
   poll: true,
   ignored: '/node_modules/'
 }
},

};

任何如何解决问题的建议将不胜感激。

标签: javascriptcssreactjswebpack

解决方案


推荐阅读