简体   繁体   English

将JSON文件从Webpack主捆绑包中移出

[英]Move JSON files from webpack main bundle to own files

I'm building a small web application, where I am loading data from multiple JSON files. 我正在构建一个小型Web应用程序,在其中从多个JSON文件加载数据。

import config from './config.json';
import data from './data.json';

console.log(config, data)

For my webpack build I want to exclude the JSON files from the bundle, since they are quite big (and could be loaded asynchronously). 对于我的webpack构建,我想从包中排除JSON文件,因为它们很大(可以异步加载)。 Currently I'm trying to use file-loader to achieve this. 目前,我正在尝试使用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'
    })
  ]
};

With this configuration I get separate files, but they won't get imported. 通过这种配置,我可以获得单独的文件,但是不会导入它们。 In this particular case the console.log() only returns the filename as strings data.json and config.json . 在这种特殊情况下, console.log()仅将文件名返回为字符串data.jsonconfig.json It seems like the actual JSON files are not loaded. 似乎实际的JSON文件未加载。

What am I doing wrong? 我究竟做错了什么? Is file-loader the way to go here? file-loader是前往此处的方式吗?

Using file-loader will not do it. 使用file-loader不会这样做。 The solution is to use the SplitChunksPlugin , which is included in webpack since version 4. For older versions use the CommonsChunkPlugin . 该解决方案是使用SplitChunksPlugin ,它包含在自的WebPack版本4.对于旧版本使用CommonsChunkPlugin

Here is a working webpack.config.json file: 这是一个有效的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'
    })
  ]
};

The files get loaded in the app (see requests in DevTools) and console.log(config, data) outputs an array/object. 文件被加载到应用程序中(请参阅DevTools中的请求), console.log(config, data)输出一个数组/对象。

However, this solution will output the JSON files as JavaScript. 但是,此解决方案会将JSON文件输出为JavaScript。 This works fine for me, but might be a problem if you rely on the files being JSON. 这对我来说很好用,但是如果您依赖于文件为JSON,则可能会出现问题。 Example for a simple config.json: 一个简单的config.json的示例:

(window.webpackJsonp=window.webpackJsonp||[]).push([[1],[function(n){n.exports={name:"test"}}]]);

If you are bothered by the source maps, you can specify an exclude rule with the SourceMapDevToolPlugin . 如果您对源地图感到困扰,则可以使用SourceMapDevToolPlugin指定exclude规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM