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.html
和index.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/