我正在构建一个小型 Web 应用程序,我从多个 JSON 文件加载数据。
import config from './config.json';
import data from './data.json';
console.log(config, data)
对于我的 webpack 构建,我想从包中排除 JSON 文件,因为它们非常大(并且可以异步加载)。目前我正在尝试使用 file-loader
来实现这一点。
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 文件。
我做错了什么? file-loader
是去这里的方式吗?
最佳答案
使用 file-loader
不会这样做。解决方案是使用 SplitChunksPlugin ,自版本 4 起包含在 webpack 中。对于旧版本,请使用 CommonsChunkPlugin .
这是一个有效的 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"}}]]);
如果您对源映射感到困扰,您可以使用 SourceMapDevToolPlugin 指定一个 exclude
规则。 .
关于javascript - 将 JSON 文件从 webpack 主包移动到自己的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55504180/