如何使用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.pswp.cn/news/391052.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391052.shtml
英文地址,請注明出處:http://en.pswp.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 了解您和您的數…