webpackwebpack-2sass-loaderextracttextwebpackplugin

Webpack 2: exclude css entry from result


I want to compile scss and js with webpack. However, as long as I use it with Symfony 3 where only some pages of the frontend use javascript components, I want to compile css to a standalone file and use the old-fashioned <link href="style.css"> instead of importing (s)css into javascript modules.

I managed to do it with the following webpack.config.js, which I supposed to produce js/script.js and css/style.css. It works, however it also produces js/style.js which I do not need nor want. I suppose the problem is that the entry "style" also produces output JS even through it is processed by ExtractTextPlugin, but how to tell webpack not to produce a javascript output for an entry?

I also tried not to use multiple entry points and add main.scss to one entry point list with index.js. It didn't produce the extra file of course, but the transpiled script.js contained references to main.scss which I do not want. I want a pure solution that manage styles completely separate from scripts.

const path = require('path');
const outputPath = path.join(__dirname, '..', 'www');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
    devtool: 'source-map',
    entry: {
        script: ['./src/js/index.js'],
        style: ['./src/scss/main.scss']
    },
    target: 'web',
    output: {
        filename: 'js/[name].js',
        path: outputPath
    },
    resolve: {
        extensions: ['.js']
    },
    module: {
        rules: [
            { // sass / scss loader for webpack
                test: /\.(sass|scss)$/,
                loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin({ // define where to save the file
            filename: 'css/[name].css',
            allChunks: true,
        })
    ]
};

Solution

  • Webpack seems to always need a source code file to bring in external styles, either CSS or Sass - I don't think there's anyway to get around that. If you just want those compiled css style files to import into your app and don't want to have an associated .js file, then just use node-sass compiler and build a .css file. Then either use the webpack css loader to bring that into your app via webpack or you can manually reference it in your html file.

    Otherwise just have a js file with a single import of the Sass styles then delete the it after the build. You will get the same css either way.