i_d_1
@i_d_1
Программист PHP

Как заставить webpack собирать css в некий asset (сейчас весь css добавляется в head в тег style)?

Вот конфиг вебпака (лоадеры):
5a6764b63c7e0642065610.png

Вот конфиг вебпака (плагины):
5a67650487a7a229142168.png

Вот так я добавляю свою SCSS:
5a676552957fd827925410.png

Вот так выглядит index.ejs:
5a67661f28fd3985713727.png

Вот так оно выглядит в результате:
5a6765d2bb01a959633975.png

а хочется нормальный css файл да еще и срсмапом

Весь конфиг целиком:

webpack.config.js:
'use strict';

/**
 * TODO: Comments?
 * TODO: HMR
 */

switch (process.env.NODE_ENV) {
    case 'prod':
    case 'production':
        module.exports = require('./webpack.config.prod');
        break;
    case 'test':
    case 'testing':
        module.exports = require('./webpack.config.test');
        break;
    case 'dev':
    case 'development':
    default:
        module.exports = require('./webpack.config.dev');
        break;
}


webpack.common.config:
'use strict';

/**
 * Please see webpack config reference for better understanding:
 * https://webpack.github.io/docs/configuration.html
 */
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    /**
     * These parameters will be used for rendering `index.html`.
     */
    metadata: {
        title: 'Demo Application',
        baseUrl: '/'
    },

    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts'
    },

    resolve: {
        extensions: ['', '.ts', '.js', '.scss', '.html'],
        modulesDirectories: ['node_modules']
    },

    module: {
        loaders: [
            /**
             * Loaders for TypeScript.
             * No need to exclude tests by `(spec|e2e)` mask here, as they are in separate directory.
             *
             * See project repository for details / configuration reference:
             * https://github.com/s-panferov/awesome-typescript-loader
             * https://github.com/TheLarkInn/angular2-template-loader
             */
            {
                test: /\.ts$/,
                loaders: ['ts-loader', 'angular2-template-loader']
            },

            /**
             * Loaders for HTML templates, JSON files, SASS/SCSS stylesheets. See details at projects' repositories:
             *
             * https://github.com/webpack/json-loader
             * https://github.com/webpack/html-loader
             * https://github.com/gajus/to-string-loader
             */
            {test: /\.json$/, loader: 'json-loader'},
            {test: /\.html$/, loader: 'raw-loader'},
            {test: /\.scss$/, loaders: [ /*'postcss-loader', */'raw-loader',  'sass-loader' ]},
            {test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|pdf)$/, loader: "file"},
            {test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ]}
        ]
    },

    plugins: [
        /**
         * Quote from webpack docs: "Assign the module and chunk ids by occurrence count. Ids that are used often get
         * lower (shorter) ids. This make ids predictable, reduces total file size and is recommended."
         *
         * See https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
         */
        new webpack.optimize.OccurenceOrderPlugin(true),

        /**
         * This plugin simplifies generation of `index.html` file. Especially useful for production environment,
         * where your files have hashes in their names.
         *
         * We have auto-injection disabled here, otherwise scripts will be automatically inserted at the end
         * of `body` element.
         *
         * See https://www.npmjs.com/package/html-webpack-plugin for details.
         *
         * TODO: Google Analytics and other stuff like that
         */
        new HtmlWebpackPlugin({
            title: 'Demo Application',
            template: 'src/index.ejs',
            chunksSortMode: 'dependency',
            // assets : {
            //     "style": "style.[hash].css",
            // },
            inject: false
        }),

        /**
         * This plugin helps to share common code between pages.
         *
         * For more info see:
         * https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
         * https://github.com/webpack/docs/wiki/optimization#multi-page-app
         */
        new webpack.optimize.CommonsChunkPlugin({
            name: ['vendor', 'polyfills']
        })
    ]
};


webpack.develop.config:
'use strict';

/**
 * TODO: Comments
 */
const webpack = require('webpack');
const ENV = process.env.ENV = process.env.NODE_ENV = 'dev';
let config = require('./webpack.config.common');

config.devtool = 'inline-source-map';

config.output = {
    path: './dist',
    publicPath: 'http://localhost:9045/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js',
    sourceMapFilename: '[name].map',
    libraryTarget: "umd",


};

console.log("server: http://localhost:9045/");

config.debug = true;

config.devServer = {
    historyApiFallback: true,
    stats: 'minimal',
    outputPath: 'dist',
    host: 'localhost',
    port: 9045,
    watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
    }
};

/**
 * Quote from webpack docs: "Define free variables. Useful for having development builds with debug logging
 * or adding global constants."
 *
 * Note, that values are _evaluated_, not just assigned (this is why we use `JSON.stringify` here).
 */
config.plugins.push(new webpack.DefinePlugin({
    'ENV': JSON.stringify(ENV),
    'process.env': {
        'ENV': JSON.stringify(ENV)
    }
}));

module.exports = config;
  • Вопрос задан
  • 897 просмотров
Решения вопроса 1
Basters
@Basters
Кокер-спаниель
Extract Text Plugin, там в доке все есть

На всякий случай пример...

{
          test: /\.scss$/,
          use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
              { loader: 'css-loader', options: { sourceMap: true } },
              { loader: 'postcss-loader', options: { sourceMap: true } },
              { loader: 'resolve-url-loader', options: { sourceMap: true } },
              { loader: 'sass-loader', options: { sourceMap: true } }
            ]
          })
        }


и ниже в плагинах

new ExtractTextPlugin('styles/[name].css'),
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы