【问题标题】:Building both CSS and Javascript files with Webpack 1使用 Webpack 1 构建 CSS 和 Javascript 文件
【发布时间】:2017-01-22 20:56:14
【问题描述】:

我试图在我的 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
    ],
};

【问题讨论】:

    标签: javascript sass webpack ecmascript-6 babeljs


    【解决方案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 插件是不同的。

    【讨论】:

    • @Quotidian 我不想从包中提取它,我想直接将 .scss 文件转换为 .css 文件,而无需先将其添加到某些 webpack javascript 包中然后从那里提取它。
    • Webpack 捆绑所有内容以保留依赖项,这就是它们提供提取插件的原因。如果你不想这样,那么 webpack 是错误的选择。
    猜你喜欢
    • 2017-08-16
    • 2018-03-11
    • 2016-09-14
    • 2018-01-30
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多