通过npm导入Sass

cal*_*rae 38 sass node.js npm node-modules

目前在我们的Sass文件中,我们有类似以下内容:

@import "../../node_modules/some-module/sass/app";
Run Code Online (Sandbox Code Playgroud)

这很糟糕,因为我们实际上并不确定路径:它可能是../node_modules,它可能是../../../../../node_modules,因为npm如何安装东西.

在Sass中我们可以搜索到找到node_modules吗?甚至是通过npm包括Sass的正确方法?

Pro*_*eek 45

如果你在2017年寻找一个方便的答案并使用Webpack,这是我发现的最简单的.

假设您的模块路径如下:

node_modules/some-module/sass/app
Run Code Online (Sandbox Code Playgroud)

然后在您的主scss文件中,您可以使用:

@import "~some-module/sass/app";
Run Code Online (Sandbox Code Playgroud)

Tilde运营商应将任何导入解析为模块.

  • 在我看来,只有你使用Webpack才能自动运行. (6认同)
  • @CTarczon这个应该在答案中提到,很多人,包括我自己,不要用Webpack来编译他们的Sass. (4认同)
  • 一年后我发现自己在这里,现在使用 Webpack ......但为什么这个解决方案有效? (2认同)

Luc*_*tta 17

正如Oncle Tom所提到的,新版本的Sass有这个新importer选项,你在Sass文件中执行的每个"导入"都将首先通过这个方法.这意味着您可以修改此方法的实际URL.

我习惯于require.resolve找到实际的模块条目文件.
看看我的gulp任务,看看它是否对你有所帮助:

'use strict';

var path       = require('path'),
    gulp       = require('gulp'),
    sass       = require('gulp-sass');

var aliases = {};

/**
 * Will look for .scss|sass files inside the node_modules folder
 */
function npmModule(url, file, done) {
  // check if the path was already found and cached
  if(aliases[url]) {
    return done({ file:aliases[url] });
  }

  // look for modules installed through npm
  try {
    var newPath = path.relative('./css', require.resolve(url));
    aliases[url] = newPath; // cache this request
    return done({ file:newPath });
  } catch(e) {
    // if your module could not be found, just return the original url
    aliases[url] = url;
    return done({ file:url });
  }
}

gulp.task("style", function() {
  return gulp.src('./css/app.scss')
    .pipe(sass({ importer:npmModule }))
    .pipe(gulp.dest('./css'));
});
Run Code Online (Sandbox Code Playgroud)

现在假设你inuit-normalize使用node 安装了.你可以在你的Sass文件中简单地"要求"它:

@import "inuit-normalize";
Run Code Online (Sandbox Code Playgroud)

我希望能帮助你和他人.因为添加相对路径总是痛苦的屁股:)

  • 棒极了!`node_modules/inuit-normalize`里面的文件名是`@import"inuit-normalize"`load? (2认同)

Kam*_*pek 16

您可以在渲染选项中添加另一个includePath.

简单的例子

基于Oncle Tom示例的片段.

var options = {
  file: './sample.scss',
  includePaths: [
    path.join(__dirname, 'bower_components'), // bower
    path.join(__dirname, 'node_modules') // npm
  ]
};

sass.render(options, function(err, result){
  console.log(result.css.toString());
});
Run Code Online (Sandbox Code Playgroud)

那应该做.您可以使用包中的文件@import "my-cool-package/super-grid

Webpack和scss-loader示例

{
  test: /\.scss$/, 
  loader: 'style!css!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true&includePaths[]=./node_modules' 
},
Run Code Online (Sandbox Code Playgroud)

注意最后一个参数,includePaths必须是数组.请记住使用正确的格式


Onc*_*Tom 7

您可以使用Sass importer函数执行此操作.参看 https://github.com/sass/node-sass#importer--v200.

以下示例说明node-sass@3.0.0和node@0.12.2:

安装凉亭依赖:

$ bower install sass-mq
$ npm install sass/node-sass#3.0.0-pre
Run Code Online (Sandbox Code Playgroud)

Sass文件:

@import 'sass-mq/mq';

body {
  @include mq($from: mobile) {
    color: red;
  }
  @include mq($until: tablet) {
    color: blue;
  }
}
Run Code Online (Sandbox Code Playgroud)

节点渲染器文件:

'use strict';

var sass = require('node-sass');
var path = require('path');
var fs = require('fs');

var options = {
  file: './sample.scss',
  importer: function bowerModule(url, file, done){
    var bowerComponent = url.split(path.sep)[0];

    if (bowerComponent !== url) {
      fs.access(path.join(__dirname, 'bower_components', bowerComponent), fs.R_OK, function(err){
        if (err) {
          return done({ file: url });
        }

        var newUrl = path.join(__dirname, 'bower_components', url);

        done({ file: newUrl });
      })
    }
    else {
      done({ file: url });
    }
  }
};

sass.render(options, function(err, result){
  if (err) {
    console.error(err);
    return;
  }

  console.log(result.css.toString());
});
Run Code Online (Sandbox Code Playgroud)

这个很简单,不是递归的.该require.resolve函数可以帮助处理树 - 或者等到npm@3.0.0以从平面依赖树中受益.


mik*_*ana 5

我专门为此制作了sass-npm模块.

npm install sass-npm
Run Code Online (Sandbox Code Playgroud)

在你的SASS中:

// Since node_modules/npm-module-name/style.scss exists, this will be imported.
@import "npm-module-name";

// Since just-a-sass-file isn't an installed npm module, it will be imported as a regular SCSS file.
@import "just-a-sass-file";
Run Code Online (Sandbox Code Playgroud)

我通常使用gulp-sass(与常规SASS具有相同的'importer'选项)

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    sassNpm = require('sass-npm')();
Run Code Online (Sandbox Code Playgroud)

然后,在您.pipe(sass())的帐户中添加导入程序:

.pipe(sass({
    paths: ['public/scss'],
    importer: sassNpm.importer,
}))
Run Code Online (Sandbox Code Playgroud)


Lit*_*Zha 5

对于dart-sass2022 年的命令行用户,只需使用以下--load-path选项:

$ npx sass --load-path=node_modules
Run Code Online (Sandbox Code Playgroud)

重要提示:整个node_modules文件夹包含这么多内容,只需将其在监视模式下启动速度设置得非常慢即可。您应该只设置包路径,例如:

$npx sass -w --load-path=node_modules/foo --load-path=node_modules/bar/scss 
Run Code Online (Sandbox Code Playgroud)