Extract text webpack plugin css

ExtractTextWebpackPlugin

Extract text from a bundle, or bundles, into a separate file.

Install

 npm install --save-dev extract-text-webpack-plugin # for webpack 2 npm install --save-dev extract-text-webpack-plugin@2.1.2 # for webpack 1 npm install --save-dev extract-text-webpack-plugin@1.0.1 

Usage

:warning: Since webpack v4 the extract-text-webpack-plugin should not be used for css. Use mini-css-extract-plugin instead.

:warning: For webpack v1, see the README in the webpack-1 branch.

const ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports =  module:  rules: [  test: /\.css$/, use: ExtractTextPlugin.extract( fallback: "style-loader", use: "css-loader" >) > ] >, plugins: [ new ExtractTextPlugin("styles.css"), ] > 

It moves all the required *.css modules in entry chunks into a separate CSS file. So your styles are no longer inlined into the JS bundle, but in a separate CSS file ( styles.css ). If your total stylesheet volume is big, it will be faster because the CSS bundle is loaded in parallel to the JS bundle.

Options

new ExtractTextPlugin(options: filename | object) 

Extract from all additional chunks too (by default it extracts only from the initial chunk(s))
When using CommonsChunkPlugin and there are extracted chunks (from ExtractTextPlugin.extract ) in the commons chunk, allChunks must be set to true

  • [name] name of the chunk
  • [id] number of the chunk
  • [contenthash] hash of the content of the extracted file
  • [:contenthash::] optionally you can configure
    • other hashType s, e.g. sha1 , md5 , sha256 , sha512
    • other digestType s, e.g. hex , base26 , base32 , base36 , base49 , base52 , base58 , base62 , base64
    • and length , the length of the hash in chars

    :warning: ExtractTextPlugin generates a file per entry, so you must use [name] , [id] or [contenthash] when using multiple entries.

    #extract

    ExtractTextPlugin.extract(options: loader | object) 

    Creates an extracting loader from an existing loader. Supports loaders of type < loader: [name]-loader ->, options: <> -> > .

    loader(e.g ‘style-loader’ ) that should be used when the CSS is not extracted (i.e. in an additional chunk when allChunks: false )

    Multiple Instances

    There is also an extract function on the instance. You should use this if you have more than one instance of ExtractTextPlugin .

    const ExtractTextPlugin = require('extract-text-webpack-plugin'); // Create multiple instances const extractCSS = new ExtractTextPlugin('stylesheets/[name]-one.css'); const extractLESS = new ExtractTextPlugin('stylesheets/[name]-two.css'); module.exports =  module:  rules: [  test: /\.css$/, use: extractCSS.extract([ 'css-loader', 'postcss-loader' ]) >,  test: /\.less$/i, use: extractLESS.extract([ 'css-loader', 'less-loader' ]) >, ] >, plugins: [ extractCSS, extractLESS ] >; 

    Extracting Sass or LESS

    The configuration is the same, switch out sass-loader for less-loader when necessary.

    const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports =  module:  rules: [  test: /\.scss$/, use: ExtractTextPlugin.extract( fallback: 'style-loader', use: ['css-loader', 'sass-loader'] >) > ] >, plugins: [ new ExtractTextPlugin('style.css') //if you want to pass in options, you can do so: //new ExtractTextPlugin( // filename: 'style.css' //>) ] > 

    url() Resolving

    If you are finding that urls are not resolving properly when you run webpack. You can expand your loader functionality with options. The url: false property allows your paths resolved without any changes.

    const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports =  module:  rules: [  test: /\.scss$/, use: ExtractTextPlugin.extract( fallback: 'style-loader', use: [  loader: 'css-loader', options:  // If you are having trouble with urls not resolving add this setting. // See https://github.com/webpack-contrib/css-loader#url url: false, minimize: true, sourceMap: true > >,  loader: 'sass-loader', options:  sourceMap: true > > ] >) > ] > > 

    Modify filename

    filename parameter could be Function . It passes getPath to process the format like css/[name].css and returns the real file name, css/js/a.css . You can replace css/js with css then you will get the new path css/a.css .

    entry:  'js/a': "./a" >, plugins: [ new ExtractTextPlugin( filename: (getPath) =>  return getPath('css/[name].css').replace('css/js', 'css'); >, allChunks: true >) ] 

    Источник

    Saved searches

    Use saved searches to filter your results more quickly

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

    [DEPRECATED] Please use https://github.com/webpack-contrib/mini-css-extract-plugin Extracts text from a bundle into a separate file

    License

    webpack-contrib/extract-text-webpack-plugin

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

    Name already in use

    A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

    Sign In Required

    Please sign in to use Codespaces.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    If you have problem(s) with migration on MiniCssExtractPlugin feel free to open issue with reproducible test repo, thanks

    Extract text from a bundle, or bundles, into a separate file.

    # for webpack 3 npm install --save-dev extract-text-webpack-plugin # for webpack 2 npm install --save-dev extract-text-webpack-plugin@2.1.2 # for webpack 1 npm install --save-dev extract-text-webpack-plugin@1.0.1

    ⚠️ Since webpack v4 the extract-text-webpack-plugin should not be used for css. Use mini-css-extract-plugin instead.

    const ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports =  module:  rules: [  test: /\.css$/, use: ExtractTextPlugin.extract( fallback: "style-loader", use: "css-loader" >) > ] >, plugins: [ new ExtractTextPlugin("styles.css"), ] >

    It moves all the required *.css modules in entry chunks into a separate CSS file. So your styles are no longer inlined into the JS bundle, but in a separate CSS file ( styles.css ). If your total stylesheet volume is big, it will be faster because the CSS bundle is loaded in parallel to the JS bundle.

    Advantages Caveats
    Fewer style tags (older IE has a limit) Additional HTTP request
    CSS SourceMap (with devtool: «source-map» and extract-text-webpack-plugin?sourceMap ) Longer compilation time
    CSS requested in parallel No runtime public path modification
    CSS cached separate No Hot Module Replacement
    Faster runtime (less code and DOM operations) .
    new ExtractTextPlugin(options: filename | object)
    • [name] name of the chunk
    • [id] number of the chunk
    • [contenthash] hash of the content of the extracted file
    • [:contenthash::] optionally you can configure
      • other hashType s, e.g. sha1 , md5 , sha256 , sha512
      • other digestType s, e.g. hex , base26 , base32 , base36 , base49 , base52 , base58 , base62 , base64
      • and length , the length of the hash in chars

      ⚠️ ExtractTextPlugin generates a file per entry, so you must use [name] , [id] or [contenthash] when using multiple entries.

      ExtractTextPlugin.extract(options: loader | object)

      Creates an extracting loader from an existing loader. Supports loaders of type < loader: [name]-loader ->, options: <> -> > .

      Name Type Description
      options.use / / Loader(s) that should be used for converting the resource to a CSS exporting module (required)
      options.fallback / / loader(e.g ‘style-loader’ ) that should be used when the CSS is not extracted (i.e. in an additional chunk when allChunks: false )
      options.publicPath Override the publicPath setting for this loader

      There is also an extract function on the instance. You should use this if you have more than one instance of ExtractTextPlugin .

      const ExtractTextPlugin = require('extract-text-webpack-plugin'); // Create multiple instances const extractCSS = new ExtractTextPlugin('stylesheets/[name]-one.css'); const extractLESS = new ExtractTextPlugin('stylesheets/[name]-two.css'); module.exports =  module:  rules: [  test: /\.css$/, use: extractCSS.extract([ 'css-loader', 'postcss-loader' ]) >,  test: /\.less$/i, use: extractLESS.extract([ 'css-loader', 'less-loader' ]) >, ] >, plugins: [ extractCSS, extractLESS ] >;

      The configuration is the same, switch out sass-loader for less-loader when necessary.

      const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports =  module:  rules: [  test: /\.scss$/, use: ExtractTextPlugin.extract( fallback: 'style-loader', use: ['css-loader', 'sass-loader'] >) > ] >, plugins: [ new ExtractTextPlugin('style.css') //if you want to pass in options, you can do so: //new ExtractTextPlugin( // filename: 'style.css' //>) ] >

      If you are finding that urls are not resolving properly when you run webpack. You can expand your loader functionality with options. The url: false property allows your paths resolved without any changes.

      const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports =  module:  rules: [  test: /\.scss$/, use: ExtractTextPlugin.extract( fallback: 'style-loader', use: [  loader: 'css-loader', options:  // If you are having trouble with urls not resolving add this setting. // See https://github.com/webpack-contrib/css-loader#url url: false, minimize: true, sourceMap: true > >,  loader: 'sass-loader', options:  sourceMap: true > > ] >) > ] > >

      filename parameter could be Function . It passes getPath to process the format like css/[name].css and returns the real file name, css/js/a.css . You can replace css/js with css then you will get the new path css/a.css .

      entry:  'js/a': "./a" >, plugins: [ new ExtractTextPlugin( filename: (getPath) =>  return getPath('css/[name].css').replace('css/js', 'css'); >, allChunks: true >) ]

      Источник

      #10 — Extract-text-plugin — плагин для подключения CSS-файлов

      Всем привет! Меня зовут Ковальчук Дмитрий. Вы смотрите Лофтскул. Мы продолжаем изучать Webpack 2.

      При помощи css-loader и style-loader на предыдущих уроках мы подружили css с Webpack. При этом весь css-код добавлялся в javascript-бандл, что, в общем-то, неплохо. Однако, когда мы имеем дело с действительно большими css-файлами, мы можем выиграть в скорости загрузки приложения, вынеся css-код в отельные файлы, которые будут загружаться в браузере параллельно с основным javascript-бандлом.

      Для этого существует специальный плагин extract-text-webpack-plugin, который мы и рассмотрим на этом видеоуроке.

      Важное замечание! Только вам самим решать, как именно подгружать ваши стили в ваше приложение: инлайном в html или отдельным файлом. Здесь нет четких законов. В академических целях для моего приложения я решил сделать так.

      Для разработки я буду подключать CSS инлайном прямо в html, что мной и было сделано на предыдущих уроках.

      А для продакшена подключу по старинке, в виде отдельных файлов. Для этого я даже создам отдельный конфиг-файл. Но всему своё время.

      Установка плагина extract-text-plugin

      Давайте начнем с установки плагина.

      yarn add extract-text-webpack-plugin -D

      Создадим файл для конфигурации.

      const ExtractTextPlugin = require(‘extract-text-webpack-plugin’);

      Источник

      Читайте также:  Java thread stop method
Оцените статью