webpack 插件:string-loader
string loader for webpack
webpack 插件:把任意的资源文件打包成可require的字符串模板
Installation
npm install string-loader --save-dev
Usage
webpack.config 配置
loaders: [ { test: /\.[name]$/, loader: "string" } ]
示例 1: 把html转换为字符串模板,以便模板引擎使用
webpack.config
loaders: [ { test: /\tpl\.html$/, loader: "string" } ]
list.tpl.html
<ul>
<% for(var i in list){ %>
<li><%= list[i].text %></li>
<% } %>
</ul>
list.js
var Template = require('template'),
TPL = require('./list.tpl.html');
var html = Template(TPL, [
{
text: 'option1'
},
{
text: 'option2'
}
]);
console.log(html); //html: '<ul><li>option1</li><li>option2</li></ul>'
示例 2: 把json数据转换为字符串
webpack.config
loaders: [ { test: /\.html|\.json$/, loader: "string" } ]
data.json
[
{
"text": "first",
"value": "first"
},
{
"text": "second",
"value": "second"
}
]
index.js
var str = require('./data');
var json = JSON.parse(str);
console.log(json); //json: [{"text": "first","value": "first"},{"text": "second","value": "second"}]
<br /> 参考: