1. json5-loader
将json5
文件解析为JavaScript对象。
1.1. 安装
npm install --save-dev json5-loader
1.2. 用法
你可以通过以下用法使用这个 loader
- 在 webpack 配置里的
module.loaders
对象中配置json5-loader
; - 直接在 require 语句中使用
json5-loader!
前缀。
假设我们有下面这个json5
文件
// appData.json5
{
env: 'production',
passwordStregth: 'strong'
}
1.2.1. webpack配置
// webpack.config.js
module.exports = {
entry: './index.js',
output: { /* ... */ },
module: {
loaders: [
{
// 使所有以 .json5结尾的文件使用 `json5-loader`
test: /\.json5$/,
loader: 'json5-loader'
}
]
}
}
// index.js
var appConfig = require('./appData.json5')
// or, in ES6
// import appConfig from './appData.json5'
console.log(appConfig.env) // 'production'
1.2.2. inline
var appConfig = require("json5-loader!./appData.json5")
// 返回的是 json 解析过的对象
console.log(appConfig.env) // 'production'
如果需要在 Node.js 中使用,不要忘记兼容(polyfill) require。更多参考 webpack 文档。