vue 프로젝트 의 설정 및 설명

12418 단어
프로젝트 구조
├── build --------------------------------- webpack      
│   ├── build.js --------------------------webpack      
│   ├── check-versions.js ------------------------------   npm,nodejs  
│   ├── logo.png ----------------------------------    logo
│   ├── utils.js ---------------------------------------       ,  css   
│   ├── vue-loader.conf.js -----------------------------   css    
│   ├── webpack.base.conf.js --------------------------- webpack    
│   ├── webpack.dev.conf.js ----------------------------      webpack  
│   ├── webpack.prod.conf.js ---------------------------      webpack  
├── config ----------------------------------     
       ├── index.js ------------------------------            
├── node_modules ----------------------------        
├── src -------------------------------------   
│   ├── assets ------------------------------     
│   ├── components --------------------------   
│   ├── main.js -----------------------------  js
│   ├── App.vue -----------------------------       
│   ├── router ------------------------------   
├── package.json ---------------------------- node    
├── .babelrc--------------------------------- babel    
├── .editorconfig----------------------------      
├── .gitignore-------------------------------   git      

웹 팩 설정 중점
프로젝트 프로필 을 보기 전에 웹 팩 에서 자주 사용 하 는 도구 와 플러그 인 을 알 아 보 겠 습 니 다. 익숙 하 다 면 이 소절 을 건 너 뛰 고 직접 보 세 요. 프로필 분석
1. path 모듈
path 는 node. js 의 모듈 로 디 렉 터 리 를 처리 하 는 대상 으로 개발 효 과 를 높 인 다.

        :
    path.join():       。          ,               ,Unix     ”/“,Windows    ”\“
    path.resolve()              

            
    __dirname:          js           
    __filename:          js      
    process.cwd():        node               


2.process
process 대상 은 Node 의 전역 대상 으로 현재 Node 프로 세 스 의 정 보 를 제공 합 니 다.

    process          ,        
    process.argv:              。
    process.env:      ,     Shell     ,  process.env.HOME
    process.pid:        


3. Source map = = 원본
쉽게 말 하면 소스 맵 은 위치 정보 가 저 장 된 정보 파일 이다.즉, 변 환 된 코드 의 모든 위치 에 대응 하 는 전환 전의 위치 다.오류 가 발생 했 을 때 debug 도 구 는 변 환 된 코드 가 아 닌 원본 코드 를 직접 표시 합 니 다.이것 은 의심 할 여지없이 개발 자 에 게 매우 큰 편 의 를 가 져 다 주 었 다.웹 팩 의 devtool 에는 7 가지 SourceMap 모드 가 있 습 니 다.
패턴
해명 하 다.
eval
각 module 은 eval 에 패키지 하여 실행 되 며, 끝 에 주석 을 추가 합 니 다 / / @ sourceURL
source-map
SourceMap 파일 을 만 듭 니 다.
hidden-source-map
source - map 와 같 지만 bundle 말미 에 주석 을 추가 하지 않 습 니 다.
inline-source-map
DataUrl 형식의 SourceMap 파일 을 만 듭 니 다.
eval-source-map
각 module 은 eval () 을 통 해 실행 되 고 DataUrl 형식의 SourceMap 을 생 성 합 니 다.
cheap-source-map
열 정보 (column - mappings) 가 없 는 Source Maps 파일 을 만 듭 니 다. loader 가 포함 되 지 않 은 sourcemap (예 를 들 어 babel 의 sourcemap)
cheap-module-source-map
열 정보 (column - mappings) 가 없 는 Source Maps 파일 을 만 드 는 동시에 loader 의 sourcemap 도 해당 줄 만 포함 하 는 것 으로 간략화 되 었 습 니 다.
4. webpack-merge
개발 환경 (development) 과 생산 환경 (production) 의 구축 목표 차이 가 크다.개발 환경 에서 우 리 는 강력 하고 실시 간 으로 다시 불 러 오기 (live reloading) 또는 열 모듈 교체 (hot module replacement) 능력 을 가 진 source map 와 localhost server 가 필요 합 니 다.한편, 생산 환경 에서 우리 의 목 표 는 더 작은 bundle, 더 가 벼 운 source map, 그리고 더욱 최적화 된 자원 에 관심 을 가지 고 로드 시간 을 개선 하 는 것 으로 바 뀌 었 다.논리 적 으로 분리 해 야 하기 때문에, 우 리 는 일반적으로 모든 환경 에 서로 독립 된 웹 팩 설정 을 작성 하 는 것 을 권장 합 니 다.일반적인 설정 부분 에서 웹 팩 - merge 를 통 해 공공 파일 을 추상 화 합 니 다. 도구 의 '유 니 버 설' 설정 은 환경 특정 설정 에서 코드 를 반복 할 필요 가 없습니다.
5. ExtractTextWebpackPlugin
ExtractTextWebpackPlugin 플러그 인 은 보통 스타일 파일 을 분리 하 는 데 사 용 됩 니 다. 분 리 된 파일 은 JS bundle 에 내장 되 지 않 고 하나의 단독 파일 에 들 어 갑 니 다. 스타일 파일 이 비교적 클 때 미리 스타일 을 불 러 올 수 있 습 니 다. 설정 예 는 다음 과 같 습 니 다.

    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    module.exports = {
       module: {
          rules: [
          {
             test: /\.css$/,
             use: ExtractTextPlugin.extract({
             fallback: "style-loader",
             use: "css-loader"
          })
       }]
    },
        plugins: [
            new ExtractTextPlugin("styles.css"),
        ]
    }


모든 입구 chunk (entry chunks) 에서 인용 한 *. css 를 독립 적 으로 분 리 된 CSS 파일 로 이동 합 니 다.따라서 스타일 은 JS bundle 에 내장 되 지 않 고 별도의 CSS 파일 (즉 styles. css) 에 넣 습 니 다.스타일 파일 크기 가 크 면 더 빨리 미리 불 러 옵 니 다. CSS bundle 은 JS bundle 과 병행 해서 불 러 옵 니 다.
6.html-webpack-plugin
웹 팩 입구 가 여러 개 있 으 면 HTML 파일 에 있 는 script 태그 에 있 습 니 다.웹 팩 의 출력 에 CSS assets 가 있다 면 (예 를 들 어 ExtractTextPlugin 을 이용 하여 CSS 를 추출 합 니 다) HTML head 의 탭 에 포 함 됩 니 다.일반적으로 개발 중, 우 리 는 CDN 과 브 라 우 저의 캐 시 를 피하 기 위해 출력 파일 bundle. js 에 hash 값 을 추가 합 니 다. 예 를 들 어  [hash].bundle.js, 사용 html-webpack-plugin 새로운 html 파일 을 만 들 때 해시 값 이 있 는 bundle. js 를 html 파일 에 참조 할 수 있 습 니 다.
7.optimize-css-assets-webpack-plugin
스 크 립 트 에서 추출 한 css 를 최적화 하 는 데 사용 합 니 다. 설정 예 는 다음 과 같 습 니 다.

    var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
    module.exports = {
      module: {
        rules: [
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
          }
        ]
      },
      plugins: [
        new ExtractTextPlugin('styles.css'),
        new OptimizeCssAssetsPlugin({
          assetNameRegExp: /\.optimize\.css$/g,
          cssProcessor: require('cssnano'),
          cssProcessorOptions: { discardComments: { removeAll: true } },
          canPrint: true
        })
      ]
    };

8.CopyWebpackPlugin
CopyWebpackPlugin 은 플러그 인 이름 에서 그의 역할 을 알 아 보기 어렵 지 않 습 니 다. 보통 자원 을 복사 하고 프로젝트 파일 을 분류 하여 통합 합 니 다.
9.friendly-errors-webpack-plugin
friendly - errors - webpack - plugin 은 터미널 에서 webapck 이 실행 하 는 경고 와 오 류 를 잘 보고 개발 체험 을 향상 시 킬 수 있 습 니 다.
10.UglifyjsWebpackPlugin
UglifyjsWebpackPlugin 은 js 코드 를 압축 하 는 데 사용 된다.
11. 개발 중인 서버 (DevServer)
웹 팩 프로젝트 서비스, 우 리 는 일반적으로 개발 단계 에서 프로젝트 의 열 리 셋, 서비스 압축, 프로젝트 에이전트 등 을 설정 합 니 다. 자주 사용 하 는 몇 가지 설정 매개 변 수 는 다음 과 같 습 니 다.

    const config = require('../config')

    // config                 

    devServer: {
        clientLogLevel: 'warning',  //               ,      ,          "none"      
         historyApiFallback: { //     HTML5 History API  ,    404             index.html
            rewrites: [
               { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
            ],
         },
         hot: true,   //        ,        
         contentBase: false,   //             。                。    ,      CopyWebpackPlugin    
         compress: true,
         host: HOST || config.dev.host,   //        。    localhost
         port: PORT || config.dev.port,   //           :
         open: config.dev.autoOpenBrowser, //open     ,      true ,             
         overlay: config.dev.errorOverlay   //                          
             ? { warnings: false, errors: true }
             : false,
         publicPath: config.dev.assetsPublicPath, //                 
         proxy: config.dev.proxyTable,           //  API   
         quiet: true,       //   quiet  ,                         ,       FriendlyErrorsPlugin      
         watchOptions: {   //            。      
               poll: config.dev.poll,
         }
    },


프로필 분석
위의 설정 을 통 해 우 리 는 웹 팩 의 자주 사용 되 는 플러그 인과 도구 에 대해 어느 정도 알 게 되 었 습 니 다. vue - cli 비계 가 우리 에 게 생 성 된 설정 상황 을 살 펴 보 겠 습 니 다.
config.js

'use strict'

const path = require('path') //       path   

module.exports = {
  dev: {

    //     
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    //         
    host: 'localhost', //            node     process.env.HOST   
    port: 8080, //        ,    node      process.env.PORT   ,            
    autoOpenBrowser: false, //             
    errorOverlay: true,   //          ,             
    notifyOnErrors: true,  //       ,           friendly-errors-webpack-plugin     
    poll: false, //           

    //        Eslint Loader       
    //     ,       ,           
    //                        

    useEslint: true,  //      

    //       eslint                      

    showEslintErrorsInOverlay: false,  //                  

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    //        ,     source map                        ,   debug
    // cheap-module-eval-source-map        cheap-module-source-map    ,   SourceMap            
    devtool: 'cheap-module-eval-source-map',

    //              vue-files   debug ,           false

    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // index.html     
    index: path.resolve(__dirname, '../dist/index.html'),

    //       
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    //     source map   

    productionSourceMap: true,
    devtool: '#source-map',

    //                gzip            ,           gzip
    //         ,          compression-webpack-plugin   
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    //    build      ,        ,                ,   npm run build --report ,       true ,false    
    bundleAnalyzerReport: process.env.npm_config_report
  }
}


check-versions.js
이 파일 은 현재 환경 에서 node 와 npm 버 전이 우리 가 필요 로 하 는 것 과 일치 하 는 지 확인 하 는 데 사 용 됩 니 다.

    'use strict'
    const chalk = require('chalk')  //            ,     chalk.blue('Hello world')
    const semver = require('semver')  //              

    const packageConfig = require('../package.json')  //    npm     ,         ,requrie     json  
    const shell = require('shelljs') //    Unix    ,          

    // cmd                     ,      
    function exec (cmd) {
      return require('child_process').execSync(cmd).toString().trim()
    }


    const versionRequirements = [
      {
        name: 'node',
        currentVersion: semver.clean(process.version),  //                ,    '  =v1.2.3  ' -> '1.2.3'     
        versionRequirement: packageConfig.engines.node // package.json   node      
      }
    ]

    if (shell.which('npm')) {
      versionRequirements.push({
        name: 'npm',
        currentVersion: exec('npm --version'),   //       
        versionRequirement: packageConfig.engines.npm //package.json   node      
      })
    }

    module.exports = function () {
      const warnings = []

      for (let i = 0; i < versionRequirements.length; i++) {
        const mod = versionRequirements[i]

        //            package.json       ,          ,           ,    warnings    
        if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
          warnings.push(mod.name + ': ' +
            chalk.red(mod.currentVersion) + ' should be ' +
            chalk.green(mod.versionRequirement)
          )
        }
      }

      //            warnings
      if (warnings.length) {
        console.log('')
        console.log(chalk.yellow('To use this template, you must update following to modules:'))
        console.log()

        for (let i = 0; i < warnings.length; i++) {
          const warning = warnings[i]
          console.log('  ' + warning)
        }

        console.log()
        process.exit(1)
      }
    }



build.js

    'use strict'

    //             node   npm     package.json        
    require('./check-versions')()

    process.env.NODE_ENV = 'production'

    const ora = require('ora')  //                    ,        ,   
    const rm = require('rimraf') //               ,   vue-cli           hash
    const path = require('path') //node     ,          
    const chalk = require('chalk') //        ,             
    const webpack = require('webpack') //webpack    
    const config = require('../config') //         ,

좋은 웹페이지 즐겨찾기