使用React和Webpack删除未使用的css

cel*_*ade 11 reactjs webpack purifycss

我正在尝试使用purify-css for WebPack 从我的应用程序中删除未使用的css类.

要构建这个项目我全光照React,scss,WebPack并PostCss建立和编译一切.

到目前为止,我能够取得进展,但有一些问题,我不知道为什么,但预期结果不正确.我有一个非常非常基本的设置来测试这些场景,所以这是我的index.html和app.js文件(到目前为止我唯一的文件):

的index.html

<body>
    <nav>
        <a href="">home</a>
    </nav>
    <hr />
    <div id="app"></div>
    <footer class="my-other-heading"></footer>
</body>
Run Code Online (Sandbox Code Playgroud)

app.js

class App extends React.Component {
    render() {
        return (
            <h1 className="my-other-heading">Mamamia!</h1>
        );
    }
}

render(<App />, window.document.getElementById("app"));
Run Code Online (Sandbox Code Playgroud)

在css文件中,我使用的是Normalize.css(带有一堆css classess),只有3个自定义类:

.my-class {
    background-color: #CCDDEE;
}

.my-heading {
    color: red;
}

.my-other-heading {
    color: blue;
}
Run Code Online (Sandbox Code Playgroud)

预期的输出应该只包含这些类:

html, body, nav, a, hr, div, footer, h1, .my-other-heading
Run Code Online (Sandbox Code Playgroud)

但它有一些其他类:

.my-heading, h2, h3, h4, [type='checkbox'] (and other similar, e.g.: [type='button']
Run Code Online (Sandbox Code Playgroud)

为什么会这样?它正在删除它应该删除的几乎所有类,但是它们中的一些仍在这里,并且显然没有在索引文件上使用的类.我不知道它们是否因为React方面的其他声明而持续存在,但我只引用了src文件.这是我的purify-css配置:

new PurifyCSSPlugin({
  paths: glob.sync([
    path.join(__dirname, '..', 'src', '**/*.html'),
    path.join(__dirname, '..', 'src', '**/*.js'),
  ]),
})
Run Code Online (Sandbox Code Playgroud)

xur*_*rei 12

根据我自己的经验(Web 开发中 15 岁以上),尝试自动删除 CSS 总是带来比它解决的更多的问题。

类名会随着运行时的变化而变化,有时会以一种意想不到的方式发生变化。自动删除 CSS 有点等同于停机问题:一般无法解决,特别是不可靠。

我不知道为什么你没有得到显然应该在那里的课程。但我认为你不应该首先尝试这样做。

到目前为止,对我来说最好/唯一的解决方案是手动进行,并尽量保持清洁。

我意识到这可能不是您正在寻找的答案。


小智 1

您可以尝试这个 webpack.config 示例,它从 CSS 和 SASS 文件中删除所有未使用的类,但是,它添加了 normalize.css 中的类

  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader',
          publicPath: '/dist'
        })
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader'],
          publicPath: '/dist'
        })
      },  
...
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack2 - purify css',
      minify: {
        collapseWhitespace: true,
      },
      hash: true,
      template: './src/index.html'
    }),
    new ExtractTextPlugin({
      filename: '[name].css',
      disable: false,
      allChunks: true
    }),
    new PurifyCSSPlugin({
      paths: glob.sync(path.join(__dirname, 'src/*.html')),
      purifyOptions: { info: true, minify: false }
    }), 
...
Run Code Online (Sandbox Code Playgroud)