sass webpack

Sass is a very popular CSS pre-processor. The intent of this tutorial is to show you how to compile Sass files within Visual Studio using Webpack. Our discussion will include minification and autoprefixing for production.

Sass是非常流行CSS预处理器。 本教程的目的是向您展示如何使用Webpack在Visual Studio中编译Sass文件。 我们的讨论将包括生产的最小化和自动前缀。

Sure, there are some plug-ins in the Visual Studio Marketplace, and it can be nice to just install a plug-in and forget about configuration. But what happens if the plug-in is not supported anymore and stops working with newer Visual Studio versions? Well, too bad. This is the case with one of the most popular compiler plug-ins on the market.

当然,Visual Studio Marketplace中有一些插件,只安装插件而不用担心配置会很好。 但是,如果不再支持该插件并停止使用较新的Visual Studio版本,会发生什么情况? 好吧,太糟糕了。 市场上最流行的编译器插件之一就是这种情况。

By configuring the compilation yourself, you will have total control over the output. Also, vendor prefixes will be added automatically to your CSS rules. How cool is that?

通过自己配置编译,您将完全控制输出。 另外,供应商前缀将自动添加到您CSS规则中。 多么酷啊?

先决条件 (Prerequisites)

You will need to have Node installed, and you can grab it here. That’s it really. You’ll also need npm, but it will also be installed with Node.

您将需要安装Node,并且可以在此处获取它。 就是这样。 您还需要npm,但它还将与Node一起安装。

创建项目 (Creating the Project)

Note: We will be creating a .NET Core MVC app, but the same principles apply to any ASP.NET MVC app. You would just need to modify the Webpack configuration a little bit to output the CSS file to the Content directory.

注意:我们将创建一个.NET Core MVC应用程序,但是相同的原理适用于任何ASP.NET MVC应用程序。 您只需要稍微修改Webpack配置即可将CSS文件输出到Content目录。

Open Visual Studio and create a new ASP.NET Core Web Application, then select Web Application (Model-View-Controller). I’m naming my project netcore-sass-webpack.

打开Visual Studio并创建一个新的ASP.NET Core Web应用程序 ,然后选择Web应用程序(Model-View-Controller) 。 我正在命名项目netcore-sass-webpack

Create a Styles folder within the root of the project. Inside it, create a Sass file and name it site.scss. Open this new Sass file and copy the following:

在项目的根目录下创建一个Styles文件夹。 在其中创建一个Sass文件,并将其命名为site.scss 。 打开这个新的Sass文件并复制以下内容:

/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification\
for details on configuring this project to bundle and minify static web assets. */
body {padding-top: 50px;padding-bottom: 20px;background: #D69655 url('../wwwroot/images/pattern.png') repeat;
}/* Wrapping element */
/* Set some basic padding to keep content from hitting the edges */
.body-content {padding-left: 15px;padding-right: 15px;
}/* Carousel */
.carousel-caption p {font-size: 20px;line-height: 1.4;
}/* Make .svg files in the carousel display properly in older browsers */
.carousel-inner .item img[src$=".svg"] {width: 100%;
}/* QR code generator */
#qrCode {margin: 15px;
}/* Hide/rearrange for smaller screens */
@media screen and (max-width: 767px) {/* Hide captions */.carousel-caption {display: none;}
}

You will notice that this is the same CSS provided by Visual Studio when we created the project, with the exception of the background rule in the body tag. Now delete the provided CSS located under wwwroot/css (both files: site.css and site.min.css). Don’t worry, we will auto-generate these with Webpack.

您会注意到,这与我们创建项目时Visual Studio提供CSS相同,但body标记中的background规则除外。 现在,删除位于wwwroot/css下的提供CSS(两个文件: site.csssite.min.css )。 不用担心,我们将使用Webpack自动生成它们。

Now, download pattern.png and place it under wwwroot/images.

现在,下载pattern.png并将其放在wwwroot/images

Create an empty JavaScript file under the root of the application and name it webpack.config.js. We will take care of this later. You should end up with the following project structure:

在应用程序的根目录下创建一个空JavaScript文件,并将其命名为webpack.config.js 。 我们稍后会处理。 您应该以以下项目结构结束:

Note: You don’t need to do the following two steps for every project, just once (unless you un-install and re-install Visual Studio).

注意:您不需要为每个项目执行以下两个步骤,只需执行一次(除非您卸载并重新安装Visual Studio)。

You will need to provide Visual Studio with the Node installation path. Go back to your project and select Tools -> Options on the left pane Projects and Solutions -> Web Package Management and add the path to Node installation at the top of the list ( C:\Program Files\nodejs or C:\Program Files (x86)\nodejs, depending if you installed the x64 or x86 version).

您将需要为Visual Studio提供Node安装路径。 返回您的项目,然后在左侧的项目和解决方案-> Web软件包管理中选择工具->优化,然后在文件的顶部ist ( C:\Program Files\ node js or C:\Program Files (x86)\ nodejs,取决于您安装的是x64还是x86版本)。

Finally download NPM Task Runner and install it — but you will need to close Visual Studio first.

最后下载并安装NPM Task Runner ,但您需要先关闭Visual Studio。

Webpack和NPM依赖性 (Webpack and NPM Dependencies)

Open Command Prompt and navigate to the root of the project and install the needed dependencies:

打开命令提示符 ,然后导航到项目的根目录并安装所需的依赖项:

cd netcore-sass-webpack\netcore-sass-webpack
npm init -y
npm i -D webpack webpack-cli node-sass postcss-loader postcss-preset-env sass-loader css-loader cssnano mini-css-extract-plugin cross-env file-loader

The first npm command initializes your package.json and the second installs your dependencies.

第一个npm命令初始化您的package.json ,第二个命令安装您的依赖项。

  • webpack, webpack-cli — Module bundler

    webpack,webpack-cli —模块捆绑器

  • node-sass — Bindings for Node to LibSass; provides support for Sass

    node-sass — Node到LibSass的绑定; 为Sass提供支持

  • postcss-loader, postcss-preset-env — PostCSS loader for Webpack to process autoprefixing and minification

    postcss-loader,postcss-preset-env —用于Webpack的PostCSS loader,用于处理自动前缀和缩小

  • sass-loader, css-loader — Webpack needs specific loaders to support Sass and CSS

    sass-loader,css-loader — Webpack需要特定的加载器来支持Sass和CSS

  • cssnano — CSS minifier

    cssnano — CSS缩小器

  • mini-css-extract-plugin — Extracts the CSS to a separate file

    mini-css-extract- plugin-将CSS提取到单独的文件中

  • cross-env — Provides support to Windows users for environment variables. We will use NODE_ENVenvironment variable

    cross-env —为Windows用户提供环境变量支持。 我们将使用NODE_ENVenvironment变量

  • file-loader — Provides support for files (images) in our CSS rules

    文件加载器 -在我们CSS规则中提供对文件(图像)的支持

At this point you can re-open the project in Visual Studio. After the project finishes loading, open package.json and add the following scripts:

此时,您可以在Visual Studio中重新打开项目。 项目加载完成后,打开package.json并添加以下脚本:

"scripts": {"dev": "webpack --watch","build": "cross-env NODE_ENV=production webpack"},
  • dev — We will bind this script whenever the project opens, and Webpack will continually watch for changes to the source Sass files, compile them, and output the separate CSS file

    dev —每当项目打开时,我们都将绑定此脚本,Webpack将继续监视源Sass文件的更改,进行编译,并输出单独CSS文件

  • build — We will bind this script before each project build and will produce the production CSS file, including minification and autoprefixing

    build —我们将在每个项目构建之前绑定此脚本,并将产生生产CSS文件,包括缩小和自动前缀

Note: The NPM scripts will run automatically using the Task Runner window. More on that later.

注意: NPM脚本将使用“ 任务运行器”窗口自动运行。 以后再说。

It is time to work on our Webpack configuration. Open webpack.config.js and copy the following:

现在是时候进行我们的Webpack配置了。 打开webpack.config.js并复制以下内容:

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const postcssPresetEnv = require("postcss-preset-env");
// We are getting 'process.env.NODE_ENV' from the NPM scripts
// Remember the 'dev' script?
const devMode = process.env.NODE_ENV !== "production";
module.exports = {// Tells Webpack which built-in optimizations to use// If you leave this out, Webpack will default to 'production'mode: devMode ? "development" : "production",
// Webpack needs to know where to start the bundling process,// so we define the Sass file under './Styles' directoryentry: ["./Styles/site.scss"],
// This is where we define the path where Webpack will place// a bundled JS file. Webpack needs to produce this file,// but for our purposes you can ignore itoutput: {path: path.resolve(__dirname, "wwwroot"),
// Specify the base path for all the styles within your// application. This is relative to the output path, so in// our case it will be './wwwroot/css'publicPath: "/css",
// The name of the output bundle. Path is also relative// to the output path, so './wwwroot/js'filename: "js/sass.js"},module: {// Array of rules that tells Webpack how the modules (output)// will be createdrules: [{// Look for Sass files and process them according to the// rules specified in the different loaderstest: /\.(sa|sc)ss$/,
// Use the following loaders from right-to-left, so it will// use sass-loader first and ending with MiniCssExtractPluginuse: [{// Extracts the CSS into a separate file and uses the// defined configurations in the 'plugins' sectionloader: MiniCssExtractPlugin.loader},{// Interprets CSSloader: "css-loader",options: {importLoaders: 2}},{// Use PostCSS to minify and autoprefix with vendor rules// for older browser compatibilityloader: "postcss-loader",options: {ident: "postcss",
// We instruct PostCSS to autoprefix and minimize our// CSS when in production mode, otherwise don't do// anything.plugins: devMode? () => []: () => [postcssPresetEnv({// Compile our CSS code to support browsers// that are used in more than 1% of the// global market browser share. You can modify// the target browsers according to your needs// by using supported queries.// https://github.com/browserslist/browserslist#queriesbrowsers: [">1%"]}),require("cssnano")()]}},{// Adds support for Sass files, if using Less, then// use the less-loaderloader: "sass-loader"}]},{// Adds support to load images in your CSS rules. It looks for// .png, .jpg, .jpeg and .giftest: /\.(png|jpe?g|gif)$/,use: [{loader: "file-loader",options: {// The image will be named with the original name and// extensionname: "[name].[ext]",
// Indicates where the images are stored and will use// this path when generating the CSS files.// Example, in site.scss I have// url('../wwwroot/images/pattern.png') and when generating// the CSS file, file-loader will output as// url(../images/pattern.png), which is relative// to '/css/site.css'publicPath: "../images",
// When this option is 'true', the loader will emit the// image to output.pathemitFile: false}}]}]},plugins: [// Configuration options for MiniCssExtractPlugin. Here I'm only// indicating what the CSS output file name should be and// the locationnew MiniCssExtractPlugin({filename: devMode ? "css/site.css" : "css/site.min.css"})]
};

Refer to the comments in the code to understand the configuration. (More readable file here.)

请参阅代码中的注释以了解配置。 ( 此处的文件更具可读性。)

Now we need to create some bindings in Task Runner Explorer. Navigate to View -> Other Windows -> Task Runner Explorer. The window will show at the bottom and you will see the scripts you created in package.json listed there under Custom. You will also see some tasks under Defaults, but you can just ignore them.

现在,我们需要在Task Runner Explorer中创建一些绑定。 导航至查看->其他 Windows- >任务运行器浏览器。 该窗口将显示在底部,您将在“自定义” 看到在package.json创建的脚本。 您还将在“故障” 看到一些任务,但是您可以忽略它们。

We need two bindings:

我们需要两个绑定:

  • Right click build -> Bindings -> Before Build — Visual Studio will run this task before each build. Remember this npm script runs Webpack for production and will optimize the CSS file.

    右键单击生成->绑定->生成之前 -Visual Studio将在每次生成之前运行此任务。 请记住,此npm脚本运行Webpack进行生产,并将优化CSS文件。

  • Right click dev -> Bindings -> Project Open — Visual Studio will run this task when you open the project. Remember this npm script runs Webpack in watch mode and will watch for any changes in your Sass files and output the processed CSS file.

    右键单击dev->绑定->打开项目-打开项目时,Visual Studio将运行此任务。 请记住,此npm脚本在监视模式下运行Webpack, 它将监视Sass文件中的所有更改并输出处理后CSS文件。

Task Runner Explorer should look like this:

Task Runner Explorer应该看起来像这样:

Note: For some reason, Visual Studio sometimes will fail to start the dev task upon opening the project. If that happens, just open the Task Explorer and run the task manually.

注意:由于某些原因,Visual Studio有时在打开项目时将无法启动开发任务。 如果发生这种情况,只需打开任务浏览器并手动运行任务即可。

You can get the full code from the GitHub repository.

您可以从GitHub存储库中获取完整的代码。

最后的想法 (Final Thoughts)

And that’s all there is too it. Since you already have Visual Studio open, none of the tasks are running. Go ahead and right click the dev task and select run. You will see the task loading and when it finishes you will see that a site.css file was created under wwwroot/css directory. Open site.scss, make a change and save it. Now open site.css, you will see your change reflected there. Cool!!

这就是全部。 由于您已经打开了Visual Studio,因此没有任何任务在运行。 继续并右键单击 开发任务,然后选择运行。 您将看到任务加载,完成后将看到在wwwroot/css目录下创建了site.css文件。 打开site.scss ,进行更改并保存。 现在打开site.css ,您将在此处看到site.css的更改。 凉!!

Run your project by pressing Ctrl + F5, you will see a site.min.css file created under wwwroot/css directory. This file was created when Task Runner ran the build script before it built the project.

通过按Ctrl + F5来运行项目,您将看到在wwwroot/css目录下创建的site.min.css文件。 该文件是在Task Runner build项目之前运行 build脚本时创建的。

The final site should look like this:

最终站点应如下所示:

I know, I know, the background is very cheesey…but I needed an image to show the Webpack file-loader in action.

我知道,我的背景非常柔和……但是我需要一个图像来展示Webpack file-loader情况。

With this configuration, you can even add support to transpile modern JavaScript (ES6+) to ES5. Look into these: @babel/core, babel-loader, @babel/preset-env.

使用此配置,您甚至可以添加支持以将现代JavaScript(ES6 +)转换到ES5。 查看以下内容: @babel/corebabel-loader@babel/preset-env

Thank you for reading, and I hope you enjoyed it. If you have any questions, suggestions, or corrections let me know in the comments below. Don’t forget to give this article a share, and you can follow me on Twitter, GitHub, Medium, LinkedIn.

感谢您的阅读,希望您喜欢它。 如果您有任何问题,建议或更正,请在下面的评论中告诉我。 不要忘记分享本文,您可以在Twitter , GitHub , Medium , LinkedIn 上关注我。

You can also visit my personal blogging site.

您也可以访问我的个人博客网站 。



Update 8/25/19: I have been building a prayer web app called "My Quiet Time - A Prayer Journal". If you would like to stay in the loop please sign up through the following link: http://b.link/mqt

19年8月25日更新:我一直在构建一个祷告网络应用程序,名为“ 我的安静时间-祷告日记 ”。 如果您想停留在循环中,请通过以下链接进行注册: http : //b.link/mqt

The app will be released before the end of the year, I have big plans for this app. To see some mockup screenshots follow the following link: http://pc.cd/Lpy7

该应用程序将在今年年底之前发布,我对此应用程序有很大的计划。 要查看一些模型截图,请点击以下链接: http : //pc.cd/Lpy7

My DMs on Twitter are open if you have any questions regarding the app

sass webpack_如何在Visual Studio和Webpack中编译Sass文件相关推荐

  1. vscode中如何创新建php文件,php – 如何在Visual Studio Code,UNIX中的所有文件中创建所有行结尾(EOL)?...

    我使用Windows 10 home,我通常使用Visual Studio Code(VSCODE)来编辑Linux Bash脚本以及PHP和JavaScript. 我没有开发任何专门用于Window ...

  2. Visual Studio 调试器中的转储文件

    Visual Studio 调试器中的转储文件 转储文件是一个快照,其显示某个时间点正在为应用执行的进程和已为应用加载的模块. 带堆信息的转储还包括该时间点的应用内存的快照. 在 Visual Stu ...

  3. 直接在Visual Studio代码编辑器中加密字符串文件

    String encryption is used everywhere in desktop & mobile software. You might not even know about ...

  4. java代码如何与界面联系在一起_如何在Visual Studio Code 中编写Java代码

    本文将展示如何在Visual Studio Code中用Java编写和运行一个简单的Hello World程序. 首先您必须在本地开发环境中安装Java SE开发工具包(JDK) Visual Stu ...

  5. 如何在Visual Studio中“添加现有项”整个目录结构?

    我有一个独立于任何C#项目的独立文件集,它们位于复杂的嵌套目录结构中. 我想以这种格式将它们添加到我正在处理的ASP.NET Web应用程序中的不同目录中; 同时保留相同的结构. 所以,我将文件夹复制 ...

  6. 如何在Visual Studio 2010中使用CppUTest建立TDD的Code Kata的环境

    CppUTest 是一个功能全面的测试框架,是为了支持在多种操作系统上开发嵌入式软件而特别设计的.CppUTest的宏被设计成不需要了解C++也可以写测试用例.这使得C程序员更容易用这个测试框架. 那 ...

  7. [译]如何在visual studio中调试Javascript

    本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...

  8. 如何在 Visual Studio 2019 中连接中国版 Azure

    点击上方蓝字关注"汪宇杰博客" 导语 做国内项目很可能用到中国版的 Azure,即世纪互联运营的 azure.cn.然而 Visual Studio 2019 默认连接的是国际版的 ...

  9. 【转】如何在 Visual Studio 2019 中连接中国版 Azure

    导语 做国内项目很可能用到中国版的 Azure,即世纪互联运营的 azure.cn.然而 Visual Studio 2019 默认连接的是国际版的 Azure,如何添加中国版订阅呢? 差点996 6 ...

最新文章

  1. 【配置文件】log4j是什么log4j
  2. rxjs 里的pipe operator
  3. Nerv --- React IE8 兼容方案
  4. 2021年电工杯B题附代码、附论文——光伏建筑一体化板块指数发展趋势分析及预测
  5. python词云图实例
  6. 高考数学圆锥曲线总结贴+杂题巧解
  7. eNSP vlan 划分实验
  8. 泱泱大中华,美丽我的家 - 俗晒网速,感受幸福
  9. python基础之布尔运算
  10. 极坐标解圆锥曲线三角形面积范围问题
  11. WPF 如何在静态资源定义字体大小
  12. HTMLa标签常用的四种链接
  13. 大学生对AI的看法调查
  14. lua 10000以内素数的个数
  15. 对话FreeRTOS创始人
  16. 有趣且重要的css知识合集(1)纯css实现div左右拖拽效果
  17. 解决excel的date函数算大小月份不准确问题
  18. 基于51单片机调频收音机 FM电台收音机系统设计
  19. Windows下react-native连接夜神模拟器
  20. android锁屏壁纸软件,Cutisan app下载

热门文章

  1. 主键约束 mysql
  2. 草稿 datagridview的显示与修改
  3. dj鲜生-让应用的模型类生效,搬家到云服务器-非本地操作
  4. 爬虫-xpath的用法强化
  5. git-管理修改-强化暂存区的意识
  6. django生产环境部署
  7. 1. 性能测试学习指南
  8. Spring AOP 的日志管理实现
  9. C# 利用位运算传递多个参数方法
  10. 《游戏设计师修炼之道:数据驱动的游戏设计》一2.3 创建漏洞:一个例子