如何使用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.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 。
上一篇: java集合框架