source

VueJ - 빌드 후 여러 js 파일이 dist에 있음

goodcode 2022. 7. 23. 14:13
반응형

VueJ - 빌드 후 여러 js 파일이 dist에 있음

"npm run build"를 실행하면 단일 build.js 파일이 아닌 javascript 파일이 4, 5개 표시됩니다.그 Javascript 파일의 크기는 약 1MB입니다.왜 그럴까?

폴더 구조는 다음과 같습니다.

여기에 이미지 설명 입력

build.displaces를 실행합니다.

// https://github.com/shelljs/shelljs
require('./check-versions')()
require('shelljs/global')
env.NODE_ENV = 'production'

var path = require('path')
var config = require('../config')
var ora = require('ora')
var webpack = require('webpack')
var webpackConfig = require('./webpack.prod.conf')

console.log(
  '  Tip:\n' +
  '  Built files are meant to be served over an HTTP server.\n' +
  '  Opening index.html over file:// won\'t work.\n'
)

var spinner = ora('building for production...')
spinner.start()

var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)
rm('-rf', assetsPath)
mkdir('-p', assetsPath)
cp('-R', 'static/*', assetsPath)

webpack(webpackConfig, function (err, stats) {
  spinner.stop()
  if (err) throw err
  process.stdout.write(stats.toString({
    colors: true,
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false
  }) + '\n')
})

webpack.syslog.conf.syslog

var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  vue: {
    loaders: utils.cssLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: true
      }
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    // extract css into its own file
    new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    })
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

module.exports = webpackConfig

.map 파일은 소스 맵입니다.

소스 맵은 변환된 소스에서 원본 소스로 매핑되는 파일로, 브라우저가 원본 소스를 재구성하고 재구성된 원본을 디버거에 표시할 수 있습니다.
§ 출처

어플리케이션의 크기가 훨씬 커지기 때문에 반드시 프로덕션에서 필요한 것은 아닙니다.어쨌든 디버깅을 할 필요가 없습니다.

다음 설정으로 끌 수 있습니다.productionSourceMap: false. config\index.js 파일을 확인하고 다음 부분을 찾습니다.

module.exports = {
  build: {
    env: require('./prod.env'),
    productionSourceMap: false
    ....

이 모든 것이 존재하는 것은 Configuration파일에 기재되어 있기 때문입니다.

manifest.js이 존재하는 이유는 다음과 같습니다.

// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated

vendor.js이 존재하는 이유는 다음과 같습니다.

// split vendor js into its own file

및 그.map파일은 디버깅을 위한 소스 맵입니다.

sourceMap: config.build.productionSourceMap

이전 설명에서 설명한 바와 같이 vue-cli의 기본 웹 팩 구성이 이렇게 설정되어 있기 때문에 이러한 메시지가 표시됩니다.보통app.js를 포함한 모든 커스텀 코드가 포함되어 있습니다..vue파일 및 주요 Javascript 파일. venodr.jsfile은 node_modules에서 Import한 모든 것을 수집하여 이 파일에 저장합니다.

예를 들어,import vueRouter from 'vue-router'vue-discript javascript가 에 배치됩니다.vendor.jsnpm의 플러그인처럼 사용되었기 때문에 파일을 작성했습니다.프로덕션 환경에서 플러그인을 자주 변경하지 않기 때문에 플러그인이 캐시되기 때문에 별도의 파일에 저장하는 것이 매우 유용합니다.앱에서 무언가를 업데이트하고 배포하면 사용자는 업데이트된 파일을 다운로드합니다.app.js모든 것을 다시 다운로드하지 않고 앱용으로 작성한 코드가 포함되어 있습니다(플러그인 + 앱).

별도의 js 번들에 플러그인을 두는 것은 많은 프레임워크/셋업에서 일반적으로 사용되는 방법입니다.(.NET MVC 번들 등)

언급URL : https://stackoverflow.com/questions/41905680/vuejs-multiple-js-files-in-dist-after-building

반응형