With Webpack, is it possible to generate CSS only, excluding the output.js?

前端 未结 4 968
春和景丽
春和景丽 2021-01-30 11:25

I\'m using Webpack with the extract-text-webpack-plugin.

In my project, I have some build scripts. One of the build scripts is supposed to bundle and minify CSS only. As

相关标签:
4条回答
  • 2021-01-30 11:32

    Unfortunately, that is currently not possible by design. webpack started as a JavaScript bundler which is capable of handling other "web modules", such as CSS and HTML. JavaScript is chosen as base language, because it can host all the other languages simply as strings. The extract-text-webpack-plugin is just extracting these strings as standalone file (thus the name).

    You're probably better off with PostCSS which provides various plugins to post-process CSS effectively.

    0 讨论(0)
  • 2021-01-30 11:33

    One solution is to execute webpack with the Node API and control the output with the memory-fs option. Just tell it to ignore the resulting js-file. Set the output.path to "/" in webpackConfig.

    var compiler = webpack(webpackConfig);
    var mfs = new MemoryFS();
    compiler.outputFileSystem = mfs;
    compiler.run(function(err, stats) {
        if(stats.hasErrors()) { throw(stats.toString()); }
        mfs.readdirSync("/").forEach(function (f) {
            if(f === ("app.js")) { return; } // ignore js-file
            fs.writeFileSync(destination + f, mfs.readFileSync("/" + f));
        })
    });
    
    0 讨论(0)
  • 2021-01-30 11:49

    You can clean up your dist folder for any unwanted assets after the done is triggered. This can be easily achieved with the event-hooks-webpack-plugin

    //
    plugins: [
            new EventHooksPlugin({
                'done': () => {
                    // delete unwanted assets 
                }
            })
        ]
    

    Good Luck...

    0 讨论(0)
  • 2021-01-30 11:54

    There is an easy way, no extra tool is required.

    There is an easy way and you don't need extra libraries except which you are already using: webpack with the extract-text-webpack-plugin.

    In short:

    Make the output js and css file have identical name, then the css file will override js file.

    A real example (webpack 2.x):

    import path from 'path'
    import ExtractTextPlugin from 'extract-text-webpack-plugin'
    
    const config = {
      target: 'web',
      entry: {
        'one': './src/one.css',
        'two': './src/two.css'
      },
      output: {
        path: path.join(__dirname, './dist/'),
        filename: '[name].css' // output js file name is identical to css file name
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
              fallback: 'style-loader',
              use: 'css-loader'
            })
          }
        ]
      },
      plugins: [
        new ExtractTextPlugin('[name].css') // css file will override generated js file
      ]
    }
    
    0 讨论(0)
提交回复
热议问题