使用Webpack 1构建CSS和Javascript文件

时间:2016-10-11 12:51:58

标签: javascript sass webpack ecmascript-6 babeljs

我试图在我的webpack.config文件中输出一个css作为js包文件,但我面临两个问题:

1)我的输出文件有一个.js扩展名,但其中一个输出文件需要是一个css文件(scss.bundle.css)。我该怎么做才能做到这一点?

2)我的加载器需要链接到正确的输出文件,我不认为它现在正常工作。

如果您能在这里帮助我,请告诉我。我认为关于webpack的知识非常有限。

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
    context: "", // directory we currently in
    devtool: debug ? "inline-sourcemap" : null,
    entry: {
        client: "./js/client.js",
        scss: "./css/compactview.scss"
    },
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].bundle.js' // when out putting we create this kind of file
    },
    module: {
        loaders: [
            {
                test: /\.js?$/, //anything thats a JS file gets run through babel-loader
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015'],
                    plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy']
                }
            },
            {
                test: /\.scss$/, // any scss files
                loaders: ['style', 'css', 'sass'],
                include:
            }
        ]
    },
    watch: true, //automatically watch files when running webpack
    plugins: debug ? [] : [ //if in debug mode, no plugins - if in production ..
        new webpack.optimize.HotModuleReplacementPlugin(),
        new webpack.optimize.DedupePlugin(), //strip out duplicate code
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), //gets rid of sourcemaps, comments, etc
    ],
};

1 个答案:

答案 0 :(得分:1)

使用ExtractTextPlugin将css从捆绑包中拉出并放入单独的css文件中。

let ExtractTextPlugin = require('extract-text-webpack-plugin');

// multiple extract instances
let extractCSS = new ExtractTextPlugin('stylesheets/[name].css');
let extractLESS = new ExtractTextPlugin('stylesheets/[name].less');

module.exports = {
  ...
  module: {
    loaders: [
      {test: /\.scss$/i, loader: extractCSS.extract(['css','sass'])},
      {test: /\.less$/i, loader: extractLESS.extract(['css','less'])},
      ...
    ]
  },
  plugins: [
    extractCSS,
    extractLESS
  ]
};

请注意,webpack 2插件不同。