7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

gulp-sass のモジュール読み込みを require から import 文に書き換える

Last updated at Posted at 2021-09-06

gulp-sass 公式のサンプルコードで、モジュール読み込み部分が require を連結させた書き方になっている。これを import に置き換えるのがわからなかったので調べた。

公式リポジトリにちゃんと書いてあった。。
Stack Overflow にドンピシャな質問と回答があったので、gulp の設定ファイルとともにメモしておく。

元 (公式サンプルコード)

gulp-sass - npm
var sass = require('gulp-sass')(require('sass'));

変更後

gulpfile.babel.js
import dartSass from 'sass';
import gulpSass from 'gulp-sass';
const sass = gulpSass( dartSass );

Sass から CSS にコンパイルする例

gulpfile.babel.js
'use strict';

import path                 from 'path';                   // Node.js Built-in
import { src, dest, watch } from 'gulp';
import dartSass             from 'sass';
import gulpSass             from 'gulp-sass';
import postcss              from 'gulp-postcss';
import cssMqpacker          from '@hail2u/css-mqpacker';   // PostCSS Plugin
import postcssFlexbugsFixes from 'postcss-flexbugs-fixes'; // PostCSS Plugin
import autoprefixer         from 'autoprefixer';           // PostCSS Plugin
import sourcemaps           from 'gulp-sourcemaps';

// Use Dart Sass ('node-sass' で Node Sass)
const sass = gulpSass( dartSass );

const rootdir = path.resolve(__dirname, '..'),
paths = {
  css: {
    src: './src/*.scss', // style.scss, custom-editor-style.scss
    dest: rootdir, // dist/assets/css
    watchScss: './src/**/*.scss'
  }
};

const buildStyles = () =>
  src(paths.css.src)
  .pipe(sourcemaps.init())
  .pipe(sass.sync({
    outputStyle: 'compressed' // 'expanded'
  })).on('error', sass.logError)
  .pipe(postcss([
    cssMqpacker(),
    postcssFlexbugsFixes(),
    autoprefixer({ // 対応ブラウザを書いた .browserslistrc を読みに行く
      // grid: 'autoplace', // default false
      // cascade: false // Use Visual Cascade, if CSS is uncompressed. Default: true
    }),
  ]))
  .pipe(sourcemaps.write('.')) // 指定無しだと圧縮CSSファイル末尾に追記
  .pipe(dest(paths.css.dest));

// Wacth tasks
const taskWatch = (done) => {
  watch(paths.css.watchScss, buildStyles);
  done();
};

// Task run
exports.buildStyles = buildStyles; // `npx gulp buildStyles`
exports.default     = taskWatch;   // `npx gulp`

参考記事

7
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?