我是 webpack 的新手。我正在尝试编写一个 AngularJS 2 网站,并且有一个要求,我希望将我的 CSS/LESS/HTML/JS/TS 文件中的某些字符串替换为从属性文件中获取的值。
我的属性文件看起来像这样:
例子.properties
branding.title=My Awesome Website
support.telephoneNumber=+441111111111
...
Run Code Online (Sandbox Code Playgroud)
我想以这种格式在我的文件中放置令牌:
示例.html
<html>
<head>${branding.title}</head>
...
</html>
Run Code Online (Sandbox Code Playgroud)
在上面的,我想加载器来代替$ {} branding.title与我真棒网站。
是否有现有的 webpack 加载器允许我在构建之前执行这些替换作为初始步骤?
我只需要某种形式的令牌替换加载器 - 我不介意包含令牌及其替换文本的文件是否与我在上面作为示例给出的格式不同。同样,我不介意在文件中定义令牌的方式(例如${branding.title})是否不同。
这可以通过使用html-webpack-plugin 来实现
在你的 webpack.config.js 文件中执行你的属性文件的导入,希望它是一些格式良好的文件类型,比如 JSON。如果没有,您将需要解析 webpack.config 中的文件。理想情况下,如果可以,只需将 .properties 文件全部设为 JSON。同时导入 html-webpack-plugin。将 html-webpack-plugin 添加到你的 plugins 数组中。然后在模板 html 文件中,您将能够访问配置中的变量。
webpack.config.js 看起来像这样:
var config = require('../pathToProperties/example.properties.json');
var HtmlWebpackPlugin = require('html-webpack-plugin');
export.module = {
// Your webpack config
//...
meta : config,
plugins : [
new HtmlWebpackPlugin({
template : './src/index.html' // Where your index.html template exists
})
]
};
Run Code Online (Sandbox Code Playgroud)
在你的 HTML 中
<head><%= webpackConfig.metadata.branding.title%></head>
Run Code Online (Sandbox Code Playgroud)
webpack.config.js
var config = require('../pathToProperties/example.properties.json');
plugins: [
...
new HtmlWebpackPlugin({
template: 'src/index.html',
metadata: config,
})
Run Code Online (Sandbox Code Playgroud)
索引.html
<title><%= htmlWebpackPlugin.options.metadata.customValue%></title>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10364 次 |
| 最近记录: |