【问题标题】:Webpack / PostCSS - Unable to use classes from the inline styles generated by WebpackWebpack / PostCSS - 无法使用 Webpack 生成的内联样式中的类
【发布时间】:2016-04-15 22:03:24
【问题描述】:

我正在尝试在 CherryPy 应用程序中设置 Webpack(PostCSS)。 Webpack 似乎可以正确生成内联样式,以下是我在 webpack.config.js 中的加载器

{ test: /\.css$/, loader: "style-loader!css-loader?modules&importLoaders=1!postcss-loader" }

当我运行“webpack”时,它似乎从我的 stylesheets/main.css 文件中正确生成了“test-class”样式,内联在主要生成的 output.js 文件中......

exports.push([module.id, ".W_8vO1mwnWhjGJpClgHqm {\n /* color: $matt; */\n color: green;\n background: red;\n}\n", ""]);

然后将生成的 output.js 文件包含在我的 main.html 页面中的脚本标记中。但是,当我尝试使用上面生成的“测试类”时,应用它对元素没有影响。在 webpack 文档中,它提到了以下内容

// in your modules just require the stylesheet // This has the side effect that a <style>-tag is added to the DOM. require("./stylesheet.css");

我不清楚这是指哪个模块。任何见解将不胜感激。

编辑:使用完整的 webpack.config.js 更新

```

const webpack = require('webpack');
const path = require('path');
//post css
var precss       = require('precss');
var autoprefixer = require('autoprefixer');


module.exports = {

  context: __dirname + '/app',
  entry: "./test.js",
  output: {
    filename: 'almostTest.js',
    path: path.join(__dirname, './static')
},
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          presets: ['es2015']
        }
      },
      {
        test:   /\.css$/,
        loader: "style-loader!css-loader?modules&importLoaders=1!postcss-loader"
      }
    ]
  },
  postcss: [
              precss,
              autoprefixer({ browsers: ['last 2 versions']  })
            ]
}

```

【问题讨论】:

    标签: webpack cherrypy postcss


    【解决方案1】:

    要在 Webpack 捆绑的应用程序中使用 CSS,您必须将 importrequire 该文件添加到您的入口文件中。

    我采取的一种做法是创建一个index.css 文件,该文件与您的index.js 条目文件位于同一位置,然后从您的index.js 文件中要求它。

    然后,在index.css 中,您需要所有其他应用的 CSS 文件。

    Here is an example of a Webpack starter I've written importing the .scss filethe main .scss file which imports all of my other components style sheets via native imports which scss-loader treats like requires.

    否则,除非样式以某种方式导入您的入口文件,否则您的应用将无法访问这些样式。

    编辑:

    我注意到您在加载程序查询中为css-loader 定义了modules=,这将默认您的css 定义为css-modulesSee here in the css-loader docs for more details

    简短回答:从加载程序定义中删除查询字符串,使其看起来像: css-loader?importLoaders=1 并且您应该能够看到您的样式并从应用程序的任何位置访问它。

    【讨论】:

    • 谢谢肖恩。我目前在我的 test.js 中需要(用作我的入口文件)require('./index.css'); 仍然没有运气。我在上面添加了完整的 webpack.config.js。
    • 为您更新了答案。我相信这是因为您使用查询字符串中的 modules 定义打开了本地 css 范围。
    • 肖恩你很准确,非常感谢!我暂时删除了 CSS 模块,改天再处理!
    猜你喜欢
    • 2020-02-29
    • 2018-07-08
    • 2018-04-02
    • 2016-05-21
    • 2019-05-17
    • 2018-10-13
    • 2016-10-24
    • 2018-10-12
    • 2017-11-07
    相关资源
    最近更新 更多