日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

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

發(fā)布時間:2023/11/29 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何使用Webpack在HTML,CSS和JavaScript之间共享变量 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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應(yīng)用的渲染速度以及靜態(tài)CSS如何更快。 但是CSS-in-JS非常受歡迎,因為除其他功能外,您可以使用JavaScript變量動態(tài)設(shè)置樣式。

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項目中重新創(chuàng)建此特權(quán)(并且我假設(shè)您知道如何使用它)。 首先,我們希望Webpack將源文件捆綁到一個靜態(tài)dist/文件夾中。

You can check out the source code here.

您可以在此處查看源代碼 。

1.設(shè)置我們的應(yīng)用 (1. Set up our app)

無聊的部分 (The boring part)

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

為本教程創(chuàng)建一個文件夾,打開您的終端,并啟動一個項目:

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中創(chuàng)建一個腳本,該腳本告訴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:

在文件夾的根目錄中,創(chuàng)建一個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 )。 在文件夾的根目錄下創(chuàng)建它:

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文件夾中。 像這樣創(chuàng)建它:

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文件夾中創(chuàng)建這些文件:

touch index.html index.js

Perfect! You’re all set. 🚀

完善! 你們都準(zhǔn)備好了 🚀

Your folder should look like this:

您的文件夾應(yīng)如下所示:

|-- 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為空。 讓我們在其中添加一些標(biāo)記,然后添加一個自定義變量:

<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語法并將數(shù)據(jù)注入其中

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

該插件將生成一個有效HTML文件。 同時,您應(yīng)該將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選項,它允許我們將對象作為參數(shù)傳遞。 在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,事情通常會變得復(fù)雜。 好吧,這很簡單:在JavaScript中,只需導(dǎo)入文件即可。 在您的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.

這將在頁面上打印我們的全局對象。 現(xiàn)在讓我們進(jìn)入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中直接使用全局變量-我們必須使用預(yù)處理器。 在此示例中,我們將使用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方面,一個插件是不夠的。 我們必須使用加載程序?qū)ASS轉(zhuǎn)換為CSS。 在這種情況下,我們需要sass-loader軟件包,因此請根據(jù)文檔進(jìn)行安裝:

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:

回到編碼。 現(xiàn)在我們有了SASS,創(chuàng)建您的樣式表文件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已建立-現(xiàn)在我們?nèi)绾蜗蚱渲凶⑷霐?shù)據(jù)? sass-loader軟件包具有prependData選項! 但是它將字符串作為參數(shù),這意味著您的數(shù)據(jù)應(yīng)如下所示: "$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對象轉(zhuǎn)換為字符串。 我沒有在npm上找到令我滿意的軟件包,所以我編寫了自己的轉(zhuǎn)換器 。 下載文件并將其添加到您的項目中(在我的示例中為utils/jsToScss.js )。

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

您最終的webpack.config.js應(yīng)該如下所示:

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:

這是您應(yīng)該看到的:

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 🧐

如果您仍在閱讀本教程,則感謝您的關(guān)注。 希望對您有幫助! Webpack是一個非常強大的工具,您應(yīng)該進(jìn)一步研究🧐

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/文件夾中,您可以看到?jīng)]有生成任何CSS。 這是因為我使用style-loader來簡化此演示。 要生成CSS文件,請查看mini-css-extract-plugin 。

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

總結(jié)

以上是生活随笔為你收集整理的如何使用Webpack在HTML,CSS和JavaScript之间共享变量的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。