node.js 通过 npm 导入 Sass
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28283652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Importing Sass through npm
提问by callumacrae
Currently in our Sass files we have something like the following:
目前在我们的 Sass 文件中,我们有如下内容:
@import "../../node_modules/some-module/sass/app";
This is bad, because we're not actually sure of the path: it could be ../node_modules, it could be ../../../../../node_modules, because of how npm installs stuff.
这很糟糕,因为我们实际上不确定路径:它可能是../node_modules,它可能是../../../../../node_modules,因为 npm 安装东西的方式。
Is there a way in Sass that we can search up until we find node_modules? Or even a proper way of including Sass through npm?
在 Sass 中有没有一种方法可以搜索直到找到 node_modules?或者甚至是通过 npm 包含 Sass 的正确方法?
回答by ProllyGeek
If you are looking for a handy answer in 2017 and are using Webpack, this was the easiest I found.
如果您正在 2017 年寻找方便的答案并且正在使用 Webpack,这是我发现的最简单的方法。
Suppose your module path is like:
假设你的模块路径是这样的:
node_modules/some-module/sass/app
Then in your main scss file you can use:
然后在您的主 scss 文件中,您可以使用:
@import "~some-module/sass/app";
Tilde operator shall resolve any import as a module.
波浪号运算符应将任何导入解析为模块。
回答by Lucas Motta
As Oncle Tom mentioned, the new version of Sass has this new importeroption, where every "import" you do on your Sass file will go first through this method. That means that you can then modify the actual url of this method.
正如 Oncle Tom 提到的,新版本的 Sass 有这个新importer选项,你对 Sass 文件所做的每一次“导入”都会首先通过这个方法。这意味着您可以修改此方法的实际 url。
I've used require.resolveto locate the actual module entry file.
Have a look at my gulp task and see if it helps you:
我曾经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'));
});
Now let's say you installed inuit-normalizeusing node. You can simply "require" it on your Sass file:
现在假设您inuit-normalize使用 node.js安装。你可以简单地在你的 Sass 文件中“要求”它:
@import "inuit-normalize";
I hope that helps you and others. Because adding relative paths is always a pain in the ass :)
我希望这能帮助你和其他人。因为添加相对路径总是很麻烦:)
回答by Kamil Jopek
You can add another includePathsto your render options.
您可以向渲染选项添加另一个includePaths。
Plain example
简单的例子
Snippet based on example from Oncle Tom.
基于 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());
});
That should do. You can include the files from package using @import "my-cool-package/super-grid
那应该做。您可以使用包含包中的文件@import "my-cool-package/super-grid
Webpack and scss-loader example
Webpack 和 scss-loader 示例
{
test: /\.scss$/,
loader: 'style!css!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true&includePaths[]=./node_modules'
},
Notice the last argument, includePaths has to be array. Keep in mind to use right format
注意最后一个参数,includePaths 必须是数组。请记住使用正确的格式
回答by Oncle Tom
You can use a Sass importerfunction to do so. Cf. https://github.com/sass/node-sass#importer--v200.
您可以使用 Sassimporter函数来执行此操作。参见 https://github.com/sass/node-sass#importer--v200。
The following example illustrates [email protected] with [email protected]:
以下示例说明了 [email protected] 和 [email protected]:
Install the bower dependency:
安装凉亭依赖:
$ bower install sass-mq
$ npm install sass/node-sass#3.0.0-pre
The Sass file:
萨斯文件:
@import 'sass-mq/mq';
body {
@include mq($from: mobile) {
color: red;
}
@include mq($until: tablet) {
color: blue;
}
}
The node renderer file:
节点渲染器文件:
'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());
});
This one is simple and not recursive. The require.resolvefunction could help to deal with the tree – or wait until [email protected] to benefit from the flat dependency tree.
这个很简单,不是递归的。该require.resolve函数可以帮助处理树 - 或者等到 [email protected] 从平面依赖树中受益。
回答by mikemaccana
I made the sass-npmmodule specifically for this.
我专门为此制作了sass-npm模块。
npm install sass-npm
In your SASS:
在您的 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";
I normally use gulp-sass (which has the same 'importer' option as regular SASS)
我通常使用 gulp-sass(与常规 SASS 具有相同的“导入器”选项)
var gulp = require('gulp'),
sass = require('gulp-sass'),
sassNpm = require('sass-npm')();
Then, in your .pipe(sass()), add the importer as an option:
然后,在您的 中.pipe(sass()),添加导入程序作为选项:
.pipe(sass({
paths: ['public/scss'],
importer: sassNpm.importer,
}))

