Javascript 将JSON文件从webpack主捆绑包移动到自己的文件
我正在构建一个小型web应用程序,从多个JSON文件加载数据Javascript 将JSON文件从webpack主捆绑包移动到自己的文件,javascript,json,webpack,Javascript,Json,Webpack,我正在构建一个小型web应用程序,从多个JSON文件加载数据 import config from './config.json'; import data from './data.json'; console.log(config, data) 对于我的webpack构建,我想从包中排除JSON文件,因为它们非常大(并且可以异步加载)。目前我正在尝试使用文件加载器来实现这一点 const path = require('path'); const CleanWebpackPlugin =
import config from './config.json';
import data from './data.json';
console.log(config, data)
对于我的webpack构建,我想从包中排除JSON文件,因为它们非常大(并且可以异步加载)。目前我正在尝试使用文件加载器
来实现这一点
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: '#cheap-source-map',
resolve: {
modules: ['node_modules']
},
entry: {
main: path.resolve('./index.js')
},
output: {
filename: '[name].bundle.js',
path: path.resolve('./dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
type: 'javascript/auto',
test: /\.json$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
inject: 'body'
})
]
};
通过这种配置,我可以得到单独的文件,但它们不会被导入。在这种特殊情况下,console.log()
仅将文件名返回为字符串data.json
和config.json
。看起来实际的JSON文件没有加载
我做错了什么?
文件加载器
就是这样吗?使用文件加载器
是不行的。解决方案是使用,它从版本4开始就包含在网页包中。对于旧版本,请使用
这是一个工作的webpack.config.json
文件:
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: '#cheap-source-map',
resolve: {
modules: ['node_modules']
},
entry: {
main: path.resolve('./index.js')
},
output: {
filename: '[name].bundle.js',
path: path.resolve('./dist')
},
optimization: {
splitChunks: {
chunks: 'all',
minSize: 0,
cacheGroups: {
data: {
test: /\.json$/,
filename: '[name].js',
name(module) {
const filename = module.rawRequest.replace(/^.*[\\/]/, '');
return filename.substring(0, filename.lastIndexOf('.'));
},
}
}
}
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
inject: 'body'
})
]
};
这些文件将加载到应用程序中(请参阅DevTools中的请求),并console.log(config,data)
输出一个数组/对象
但是,此解决方案将JSON文件输出为JavaScript。这对我来说很好,但如果依赖JSON文件,可能会有问题。简单config.json的示例:
(window.webpackJsonp=window.webpackJsonp||[]).push([[1],[function(n){n.exports={name:"test"}}]]);
如果您对源映射感到不安,可以使用指定一个排除
规则