如何使用Webpack在HTML,CSS和JavaScript之间共享变量

Earlier this week, I read an article explaining how CSS-in-JS slows down the rendering of some React apps and how static CSS is faster. But CSS-in-JS is very popular because, among other features, you can style dynamically using JavaScript variables.

本周初,我读了一篇文章,解释CSS-in-JS如何减慢某些React应用的渲染速度以及静态CSS如何更快。 但是CSS-in-JS非常受欢迎,因为除其他功能外,您可以使用JavaScript变量动态设置样式。

In this tutorial, I will show you how to recreate this perk in any of your web projects thanks to Webpack (and I assume you know how to use it). To start, we want Webpack to bundle our source files into a static dist/ folder .

在本教程中,我将向您展示如何借助Webpack在任何Web项目中重新创建此特权(并且我假设您知道如何使用它)。 首先,我们希望Webpack将源文件捆绑到一个静态dist/文件夹中。

You can check out the source code here.

您可以在此处查看源代码 。

1.设置我们的应用 (1. Set up our app)

无聊的部分 (The boring part)

Create a folder for this tutorial, open your terminal, and init a project:

为本教程创建一个文件夹,打开您的终端,并启动一个项目:

npm init -y

First things first, if it’s not already done, install node.js and Webpack:

首先,如果尚未完成,请安装node.js和Webpack :

npm install webpack webpack-cli --save-dev

Let’s create a script in our package.json that tells Webpack to use our config file:

让我们在package.json中创建一个脚本,该脚本告诉Webpack使用我们的配置文件:

"scripts": {"build": "webpack --config webpack.config.js"}

At the root of your folder, create a globals.js file, where our shared variables will be stored:

在文件夹的根目录中,创建一个globals.js文件,其中将存储我们的共享变量:

module.exports = {myTitle: 'Hello freeCodeCamp!',myColor: '#42ff87',
};

The Webpack config file looks like this (webpack.config.js). Create it at the root of your folder:

Webpack配置文件看起来像这样( webpack.config.js )。 在文件夹的根目录下创建它:

module.exports = {entry: __dirname + '/app/index.js',output: {path: __dirname + '/dist',filename: 'index_bundle.js'},
};

Our source code will be located in an app folder. Create it like this:

我们的源代码将位于app文件夹中。 像这样创建它:

mkdir app && cd app

You’ll need index.html and index.js files at this point. Create those files in the app folder:

此时,您将需要index.htmlindex.js文件。 在app文件夹中创建这些文件:

touch index.html index.js

Perfect! You’re all set. 🚀

完善! 你们都准备好了 🚀

Your folder should look like this:

您的文件夹应如下所示:

|-- node_modules/
|-- package.json
|-- webpack.config.js
|-- globals.js
|-- app/|-- index.html|-- index.js

2.使用html-webpack-plugin渲染我们HTML文件 (2. Render our HTML files with the html-webpack-plugin)

This app/index.html is empty. Let’s add some markup in it and then add a custom variable:

app/index.html为空。 让我们在其中添加一些标记,然后添加一个自定义变量:

<html lang="en">
<head><title>Webpack shared variables!</title>
</head>
<body><h1><%= myTitle %></h1>
</body>
</html>

As you can see, we are trying to print a variable in our HTML... which is impossible! To make it work we’ll use the html-webpack-plugin that gives us the ability to use EJS syntax and inject data into it.

如您所见,我们正在尝试在HTML中打印变量...这是不可能的! 为了使其正常工作,我们将使用html-webpack-plugin ,它使我们能够使用EJS语法并将数据注入其中

The plugin will generate a valid HTML file. In the meantime, you should rename your app/index.html file to app/index.ejs.

该插件将生成一个有效HTML文件。 同时,您应该将app/index.html文件重命名为app/index.ejs

npm install --save-dev html-webpack-plugin

Let’s go back to our configuration file. html-webpack-plugin has an interesting templateParameters option that allows us to pass an object as parameter. Enable the plugin as follows in webpack.config.js:

让我们回到我们的配置文件。 html-webpack-plugin有一个有趣的templateParameters选项,它允许我们将对象作为参数传递。 在webpack.config.js启用插件,如下所示:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const globals = require('./globals.js')module.exports = {// ... previous config, entry, output...plugins: [new HtmlWebpackPlugin({template: 'app/index.ejs',templateParameters: globals,})]
};

Run npm run build and ta-daaaaa « <%= myTitle %> » became « Hello freeCodeCamp » ! The work is done by Webpack during the compilation when it runs the html-webpack-plugin.

运行npm run build然后ta-daaaaa «<%= myTitle%>»变成了«Hello freeCodeCamp»! 该工作由Webpack在运行html-webpack-plugin

See? This was pretty simple with the right tool: HTML ✅

看到? 使用正确的工具,这很简单:HTML✅

3.在JavaScript中使用我们的变量 (3.  Use our variables in JavaScript)

Phew, so many lines just to print a variable! 😱With Webpack, things often get complicated. Well, this one is very simple: in JavaScript just import your file. In your app/index.js:

ew,这么多行只是为了打印变量! Web使用Webpack,事情通常会变得复杂。 好吧,这很简单:在JavaScript中,只需导入文件即可。 在您的app/index.js

import globals from '../globals.js'document.write(
'<pre>' +JSON.stringify(globals, null, 2) +
'</pre>'
);

This will print our globals object on the page. Now let’s move on to the CSS.

这将在页面上打印我们的全局对象。 现在让我们进入CSS。

4.在我们CSS中使用共享变量 (4. Use shared variables in our CSS)

Here is our final boss 👾

这是我们最后的老板👾

Okay guys you got me… I lied. We can’t use our globals directly in CSS – we must use a pre-processor. In this example, we will use SASS.

好的,你们让我...我撒了谎。 我们不能在CSS中直接使用全局变量-我们必须使用预处理器。 在此示例中,我们将使用SASS 。

On the Webpack side, a plugin will not be enough. We must use a loader to convert SASS into CSS. In this case we need the sass-loader package, so install it according to the docs:

在Webpack方面,一个插件是不够的。 我们必须使用加载程序将SASS转换为CSS。 在这种情况下,我们需要sass-loader软件包,因此请根据文档进行安装:

npm install sass-loader node-sass css-loader style-loader --save-dev

Back to coding. Now that we have SASS, create your style sheet file, app/style.scss:

回到编码。 现在我们有了SASS,创建您的样式表文件app/style.scss

h1 {color: $myColor;
}

Our SASS is set up – now how can we inject data into it? The sass-loader package has a prependData option! But it takes a string as a parameter, which means that your data should look like this: "$myColor: red; myTitle: '...'";.

我们的SASS已建立-现在我们如何向其中注入数据? sass-loader软件包具有prependData选项! 但是它将字符串作为参数,这意味着您的数据应如下所示: "$myColor: red; myTitle: '...'";

We have to automate that and convert a JavaScript object into a string. I didn’t find a package on npm that satisfied me, so I wrote my own converter. Download the file and add it to your project (in my example it's utils/jsToScss.js).

我们必须使其自动化,然后将JavaScript对象转换为字符串。 我没有在npm上找到令我满意的软件包,所以我编写了自己的转换器 。 下载文件并将其添加到您的项目中(在我的示例中为utils/jsToScss.js )。

Your final webpack.config.js should look like this:

您最终的webpack.config.js应该如下所示:

const globals = require("./globals.js");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const jsToScss = require("./utils/jsToScss.js");module.exports = {entry: __dirname + "/app/index.js",output: {path: __dirname + "/dist",filename: "index_bundle.js"},plugins: [new HtmlWebpackPlugin({template: "app/index.ejs",templateParameters: globals})],module: {rules: [{test: /\.s[ac]ss$/i,use: [// Creates `style` nodes from JS strings"style-loader",// Translates CSS into CommonJS"css-loader",// Compiles Sass to CSS{loader: "sass-loader",options: {prependData: jsToScss(globals)}}]}]}
};

Here is what you should see:

这是您应该看到的:

If you are still reading this tutorial, thanks for your attention. I hope it helps you! Webpack is a very powerful tool you should dig more into 🧐

如果您仍在阅读本教程,则感谢您的关注。 希望对您有帮助! Webpack是一个非常强大的工具,您应该进一步研究🧐

NB: In your dist/ folder you can see there isn't any CSS generated. That's because I use the style-loader to keep this demo simple. To generate the CSS file, take a look at the mini-css-extract-plugin.

注意:在dist/文件夹中,您可以看到没有生成任何CSS。 这是因为我使用style-loader来简化此演示。 要生成CSS文件,请查看mini-css-extract-plugin 。

翻译自: https://www.freecodecamp.org/news/how-to-share-variables-across-html-css-and-javascript-using-webpack/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391052.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java中获得了方法名称的字符串,怎么样调用该方法

问题&#xff1a; Java中获得了方法名称的字符串&#xff0c;怎么样调用该方法 如果我有以下两个变量 Object obj; String methodName "getName";在不知道obj的类的情况下&#xff0c;我怎么样才能调用该类的名叫methodName的方法呢&#xff1f; 这个方法被调用时…

经验主义 保守主义_为什么我们需要行动主义-始终如此。

经验主义 保守主义It’s been almost three months since George Floyd was murdered and the mass protests. Three months since the nationwide protests, looting and riots across America.距离乔治弗洛伊德(George Floyd)被谋杀和大规模抗议活动已经快三个月了。 全国抗议…

Begin

Hello everyone, Finally,a technician from feiyang help me solve the question. Even though it is not the linux version i want.emmm...linux mint a new one i dont know about it And, lets make the life regular and delicate转载于:https://www.cnblogs.com/lxc-run…

redis介绍以及安装

一、redis介绍 redis是一个key-value存储系统。和Memcached类似&#xff0c;它支持存储的values类型相对更多&#xff0c;包括字符串、列表、哈希散列表、集合&#xff0c;有序集合。 这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作&#xff0c;而且…

java python算法_用Java,Python和C ++示例解释的搜索算法

java python算法什么是搜索算法&#xff1f; (What is a Search Algorithm?) This kind of algorithm looks at the problem of re-arranging an array of items in ascending order. The two most classical examples of that is the binary search and the merge sort algor…

Java中怎么把文本追加到已经存在的文件

Java中怎么把文本追加到已经存在的文件 我需要重复把文本追加到现有文件中。我应该怎么办&#xff1f; 回答一 你是想实现日志的目的吗&#xff1f;如果是的话&#xff0c;这里有几个库可供选择&#xff0c;最热门的两个就是Log4j 和 Logback了 Java 7 对于一次性的任务&a…

python机器学习预测_使用Python和机器学习预测未来的股市趋势

python机器学习预测Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works withou…

线程系列3--Java线程同步通信技术

上一篇文章我们讲解了线程间的互斥技术&#xff0c;使用关键字synchronize来实现线程间的互斥技术。根据不同的业务情况&#xff0c;我们可以选择某一种互斥的方法来实现线程间的互斥调用。例如&#xff1a;自定义对象实现互斥&#xff08;synchronize("自定义对象")…

Python数据结构之四——set(集合)

Python版本&#xff1a;3.6.2 操作系统&#xff1a;Windows 作者&#xff1a;SmallWZQ 经过几天的回顾和学习&#xff0c;我终于把Python 3.x中的基础知识介绍好啦。下面将要继续什么呢&#xff1f;让我想想先~~~嗯&#xff0c;还是先整理一下近期有关Python基础知识的随笔吧…

volatile关键字有什么用

问题&#xff1a;volatile关键字有什么用 在工作的时候&#xff0c;我碰到了volatile关键字。但是我不是非常了解它。我发现了这个解释 这篇文章已经解释了问题中的关键字的细节了&#xff0c;你们曾经用过它吗或者见过正确使用这个关键字的样例 回答 Java中同步的实现大多是…

knn 机器学习_机器学习:通过预测意大利葡萄酒的品种来观察KNN的工作方式

knn 机器学习Introduction介绍 For this article, I’d like to introduce you to KNN with a practical example.对于本文&#xff0c;我想通过一个实际的例子向您介绍KNN。 I will consider one of my project that you can find in my GitHub profile. For this project, …

MMU内存管理单元(看书笔记)

http://note.youdao.com/noteshare?id8e12abd45bba955f73874450e5d62b5b&subD09C7B51049D4F88959668B60B1263B5 笔记放在了有道云上面了&#xff0c;不想再写一遍了。 韦东山《嵌入式linux完全开发手册》看书笔记转载于:https://www.cnblogs.com/coversky/p/7709381.html

Java中如何读取文件夹下的所有文件

问题&#xff1a;Java中如何读取文件夹下的所有文件 Java里面是如何读取一个文件夹下的所有文件的&#xff1f; 回答一 public void listFilesForFolder(final File folder) {for (final File fileEntry : folder.listFiles()) {if (fileEntry.isDirectory()) {listFilesFor…

github pages_如何使用GitHub Actions和Pages发布GitHub事件数据

github pagesTeams who work on GitHub rely on event data to collaborate. The data recorded as issues, pull requests, and comments become vital to understanding the project.在GitHub上工作的团队依靠事件数据进行协作。 记录为问题&#xff0c;请求和注释的数据对于…

c# .Net 缓存 使用System.Runtime.Caching 做缓存 平滑过期,绝对过期

1 public class CacheHeloer2 {3 4 /// <summary>5 /// 默认缓存6 /// </summary>7 private static CacheHeloer Default { get { return new CacheHeloer(); } }8 9 /// <summary>10 /// 缓存初始化11 /// </summary>12 …

python 实现分步累加_Python网页爬取分步指南

python 实现分步累加As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry.作为数据科学家&#xff0c;我们一直在寻找…

Java 到底有没有析构函数呢?

Java 到底有没有析构函数呢&#xff1f; ​ ​ Java 到底有没有析构函数呢&#xff1f;我没能找到任何有关找个的文档。如果没有的话&#xff0c;我要怎么样才能达到一样的效果&#xff1f; ​ ​ ​ 为了使得我的问题更加具体&#xff0c;我写了一个应用程序去处理数据并且说…

关于双黑洞和引力波,LIGO科学家回答了这7个你可能会关心的问题

引力波的成功探测&#xff0c;就像双黑洞的碰撞一样&#xff0c;一石激起千层浪。 关于双黑洞和引力波&#xff0c;LIGO科学家回答了这7个你可能会关心的问题 最近&#xff0c;引力波的成功探测&#xff0c;就像双黑洞的碰撞一样&#xff0c;一石激起千层浪。 大家兴奋之余&am…

如何使用HTML,CSS和JavaScript构建技巧计算器

A Tip Calculator is a calculator that calculates a tip based on the percentage of the total bill.小费计算器是根据总账单的百分比计算小费的计算器。 Lets build one now.让我们现在建立一个。 第1步-HTML&#xff1a; (Step 1 - HTML:) We create a form in order to…

用于MLOps的MLflow简介第1部分:Anaconda环境

在这三部分的博客中跟随了演示之后&#xff0c;您将能够&#xff1a; (After following along with the demos in this three part blog you will be able to:) Understand how you and your Data Science teams can improve your MLOps practices using MLflow 了解您和您的数…