如何在 webpack 中加载 CSS 的根路径

Posted

技术标签:

【中文标题】如何在 webpack 中加载 CSS 的根路径【英文标题】:How to root path loading of CSS in webpack 【发布时间】:2017-12-17 13:26:00 【问题描述】:

以下css加载不起作用。import style from 'common/style.css'

可以通过根路径读取javascriptimport Score from 'components/score'

你能给我一些建议吗?

源代码树

.
└── src
    ├── app.js
    ├── common
    │   └── style.css
    ├── components
    │   ├── box.js
    │   └── score.js
    └── index.ejs

score.js

import React from 'react'
import style from 'common/style.css' // <= It is not loaded here

class Score extends React.Component 
  render() 
    return <div styleName="style.score">25</div>
  


export default Score

webpack.config.js

const webpack = require('webpack')
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')

module.exports = 
  entry: 
    app: './src/app.js'
  ,
  output: 
    path: path.resolve(__dirname, 'public'),
    publicPath: "/",
  ,
  module: 
    rules: [
      
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      ,
      
        test: /\.css$/,
        use: [
          'style-loader',
          
            loader: 'css-loader',
            options: 
              modules: true,
              localIdentName: "[path]___[name]__[local]___[hash:base64:5]"
            
          
        ],
      
    ]
  ,
  plugins: [
    new HtmlWebpackPlugin(
      template: 'src/index.ejs'
    )
  ],
  devtool: 'source-map',
  resolve: 
    modules: [
      path.resolve(__dirname, "src"),
      "node_modules"
    ],
    extensions: ['.js', '.css'],
  

错误日志

ERROR in ./src/components/score.js
Module build failed: Error: /Users/yoneapp/Desktop/webpack-css-load-sample/src/components/score.js: Cannot find module 'common/style.css'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.resolve (internal/module.js:27:19)
    at getTargetResourcePath (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-plugin-react-css-modules/dist/index.js:99:20)
    at PluginPass.ImportDeclaration (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-plugin-react-css-modules/dist/index.js:127:36)
    at newFn (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/index.js:114:17)
    at NodePath.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:115:19)
    at TraversalContext.visitQueue (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:192:19)
 @ ./src/components/box.js 13:13-40
 @ ./src/app.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/app.js

演示代码

https://github.com/yoneapp/webpack-css-load-sample

【问题讨论】:

'common/style.css'改成'../common/style.css' 【参考方案1】:

尝试在 resolve 块内添加别名,它应该告诉 Webpack 解析从 common//src/common 的所有导入:

    resolve: 
        extensions: ['.js'],
        alias: 
          common: path.resolve(__dirname, 'src/common/'),
        
    ,

此外,您也不需要在 extensions 数组中包含 .css。这仅在自动解析没有扩展名的文件时需要,但您可能不想对样式执行此操作,因此您可以在代码中清楚地指示样式表和 Javascript 文件。

更改导入路径的其他解决方案也可以,但是您会发现,一旦您获得超过 3 个级别的深度,编写 ../../../../common/style.css 将变得非常累人。别名允许您指定解析导入的根级别,如果您的 src 目录的根目录中有常量、数据存储等文件夹,则尤其有用。

如果您想了解更多关于别名的信息,Webpack 文档here 是一个很好的资源。您也可以使用别名做其他事情,例如完全匹配。

【讨论】:

【参考方案2】:

鉴于您的项目结构,我认为您使用错误的路径将样式表导入组件。

从你的一个组件中试试这个:

import style from '../common/style.css'

【讨论】:

【参考方案3】:

像下面这样添加双点和斜线

import style from '../common/style.css'
import Score from '../components/score'

【讨论】:

【参考方案4】:

Dwayne Charrington 的建议

这个方法成功了一半。

ERROR in ./src/components/score.js
Module build failed: Error: /Users/yoneapp/Desktop/webpack-css-load-sample/src/components/score.js: Cannot find module 'common/style.css'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.resolve (internal/module.js:18:19)
    at getTargetResourcePath (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-plugin-react-css-modules/dist/index.js:99:20)
    at PluginPass.ImportDeclaration (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-plugin-react-css-modules/dist/index.js:127:36)
    at newFn (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/index.js:114:17)
    at NodePath.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/path/context.js:115:19)
    at TraversalContext.visitQueue (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/Users/yoneapp/Desktop/webpack-css-load-sample/node_modules/babel-traverse/lib/index.js:114:17)
 @ ./src/components/box.js 13:13-31
 @ ./src/app.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/app.js

别名应该是成功,但是,失败了。 当 babel-plugin-react-css-modules 被移除时,它起作用了。

终于变成了这个样子。

score.js

import React from 'react'
import styles from 'common/style.css'
import CSSModules from 'react-css-modules'

class Score extends React.Component 
  render() 
    return <div styleName="score">25</div>
  


export default CSSModules(Score, styles)

webpack.config.js

const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require("extract-text-webpack-plugin")

module.exports = 
  entry: 
    app: './src/app.js'
  ,
  output: 
    filename: 'assets/[name].[chunkhash].js',
    path: path.resolve(__dirname, 'public'),
    publicPath: "/",
  ,
  module: 
    rules: [
      
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      ,
      
        test: /\.css$/,
        use: [
          'style-loader',
          
            loader: 'css-loader',
            options: 
              modules: true,
              localIdentName: "[path]___[name]__[local]___[hash:base64:5]"
            
          
        ]
      
    ]
  ,
  plugins: [
    new HtmlWebpackPlugin(
      template: 'src/index.ejs'
    )
  ],
  resolve: 
    alias: 
      common: path.resolve(__dirname, 'src/common')
    
  ,
  devtool: 'source-map'

https://github.com/yoneapp/webpack-css-load-sample/tree/success

【讨论】:

以上是关于如何在 webpack 中加载 CSS 的根路径的主要内容,如果未能解决你的问题,请参考以下文章

如何在使用“react-frame-component”库创建的 IFrame 中加载 webpack 提供的 css?

如何在 webpack 模块中加载备用 jquery?

使用 Webpack 在 React 中加载图像

如何使用 webpack 在 js 文件中加载 CDN 或外部供应商 javascript lib,而不是在 html 文件中

使用 react、webpack 和 express 无法在浏览器中加载图像

如何在 vuejs 和 webpack 中加载字体文件?