私の手書きVUE-CLI

WebPACKのおおよそこのレコードそれにプロセスを学びます。

VUE-CLIリファレンスを作成します。cli.vuejs.org/zh/guide/in ...

$ yarn global add @vue/cli
$ vue -V // 查看版本
$ vue init webpack vue-cli
复制代码

そして、プロジェクト構造を初期化し、他は.gitignoreを追加私の-VUE-CLIを作成します。

$ npm init
$ git init
复制代码

1.初期のWebPACK

webpack.docschina.org/guides/inst...

// webpack 4.x+
$ yarn add webpack webapck-cli -D
复制代码

2.プロジェクト構造を追加します。

  • エントリ・ファイル:SRC / main.jsは、main.jsに何気なくJSについて書きます。
  • HTMLテンプレートファイル:index.htmlを
  • WebPACKのプロフィール:webpack.config.js

3. WebPACKの基本構成

// webpack.config.js
const path = require('path')

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].[hash:8].js'
  }
}
复制代码
// package.json
{
    "scripts": {
        "build": "webpack",
    }
}
复制代码

$ yarn build、DIST /アプリを生成します。**。JS、アプリ。**。jsは、ブラウザのコンソールで実行してみてください。(WebPACKのwebapck.config.jsコマンドが自動的に見つけて、実行されます)。

4.使用devServer、HtmlWebpackPlugin

WebPACKの-devのサーバー

$ yarn add webpack-dev-server -D
$ yarn add html-webpack-plugin -D
复制代码
  plugins: [
    new HtmlWebpackPlugin({ template: path.resolve(__dirname, './index.html') })
  ],

  devServer: {
    // https: true,
    open: true,
    host: '0.0.0.0',
    port: 8000,
    disableHostCheck: true,
    hot: true,
    proxy: {//配置跨域,访问的域名会被代理到本地的3000端口
      '/api': 'http://localhost:3000'
    }
  }
复制代码

バベル・ローダーを使用して翻訳ES6、ES7

webpack.docschina.org/loaders/bab ...
6 @ 7バベルコア@ //注意バベルローダとの使用を支持する。バベルローダバベルコア@で使用される8 7 @。

$ yarn add babel-loader babel-core babel-preset-env babel-preset-stage-2 -D
$ yarn add babel-plugin-transform-runtime babel-runtime -D
复制代码

追加.babelrcファイルを

{
  // presets 告诉 babel 源码使用了哪些新的语法特性。
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ],
    "stage-2"
  ],
  // 生成的文件中,不产生注释, 会使 /* webpackChunkName: 'helloWorld' */ 失效
  // "comments": false,
  "plugins": [
    [
      // babel-plugin-transform-runtime 减少冗余代码,依赖 babel-runtime
      "transform-runtime",
      {
        "helpers": true,
        "polyfill": true,
        "regenerator": true,
        "moduleName": "babel-runtime"
      }
    ]
  ],
  "env": {
    // 测试环境,test 是提前设置的环境变量,如果没有设置BABEL_ENV, 则使用NODE_ENV,如果都没有设置默认就是development
    "test": {
      "presets": [
        "env",
        "stage-2"
      ],
      // instanbul是一个用来测试转码后代码的工具
      "plugins": [
        "istanbul"
      ]
    }
  }
}
复制代码
// webpack.config.js
module.exports = {
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                loaders: [
                    {
                      loader: 'babel-loader',
                      options: {
                        cacheDirectory: true,
                      },
                    },
                  ],
            },
        ]
    }
}
复制代码

6.アクセス少なく、postcss

$ yarn add less less-loader css-loader style-loader -D
$ yarn add postcss-loader autoprefixer -D
复制代码

追加.postcssrcのファイルを。

{
  "plugins": {
    "autoprefixer": {
      "browsers": ["IOS>=7", "Android>=4.1", "IE>=9"],
    }
  }
}

复制代码

7.認識.vueファイル

$ yarn add vue-loader vue-template-compiler -D
$ yarn add vue
复制代码
resolve: {
    alias: {
      vue$: 'vue/dist/vue.runtime.esm.js'
    },
  },
复制代码

8.ファイル(ファイル・ローダー+リミット機能に基づく)URL-ローダー

$糸は、URLローダーを追加-D

{
  test: /\.(jpg|jpeg|gif|png|svg|webp)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 8192,
        name: 'assets/images/[hash:8].[ext]',
      }
    }
  ]
},
{
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        name: 'assets/fonts/[hash:8].[ext]',
      }
    }
  ]
},
复制代码

9.アクセスVUE-ルータ

$糸追加VUE-​​ルータ

// 添加别名
resolve: {
    alias: {
      "@": path.resolve(__dirname, 'src')
    },
  },

// 按需加载, 注意.babelrc中: "comments": false,会使 /* webpackChunkName: 'helloWorld' */ 失效
const HelloWorld = () => import(/* webpackChunkName: 'helloWorld' */ '@/components/HelloWorld');
复制代码

10.クリーンWebPACKの-プラグイン

const CleanWebpackPlugin = require('clean-webpack-plugin');
plugins: [
  new CleanWebpackPlugin(), // 多版本共存模式时 必须要取消这个插件
]
复制代码

11.追加eslint + pritter +プリコミットフック制約コードの配信

$ yarn add babel-eslint eslint eslint-config-standard eslint-plugin-html eslint-plugin-promise eslint-plugin-standard eslint-plugin-import eslint-plugin-node -D
$ yarn add eslint-loader -D
$ yarn add prettier -D --exact
$ yarn add eslint-plugin-prettier eslint-config-prettier eslint-plugin-vue -D
// lint-staged、 husky插件,这样再每次 commit 代码的时候都会格式化一下。
$ yarn add lint-staged husky@next -D
复制代码
// 添加 .eslintrc.js
// 添加.prettierrc

// package.json
// pre-commit 约束代码提交
"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
"lint-staged": {
    "*.{js,json,css,md,vue}": ["prettier --write", "git add"]
  }

// webpack.config.js
module: {
  rules: [
     {
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        exclude: /(node_modules|bower_components)/,
      },
  ]
}
复制代码

12. CopyWebpackPlugin

// copy custom static assets
new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, './static'),
    to: 'static',
    ignore: ['.*'],
  },
]),
复制代码

最適化

1.環境を区別

異なる環境、プラグインを使用して異なる構成。$糸はクロスENVを追加-D

// package.json
scripts: {
  "build": "cross-env NODE_ENV=production webpack",
}

// 使用
porcess.env.NODE_ENV
复制代码

2.モード

webpack.docschina.org/concepts/mo ... webpack4 + MODEは、多くの構成を簡素化します。

const mode = process.env.NODE_ENV || 'development'

module.exports = {
  mode: mode,
}
复制代码

3.出力ファイルのバージョン管理

--hot開発環境はcontenthash、chunkhashを使用することはできません

const chunkhash = isDev ? '[name].[hash:8].js' : '[name].[chunkhash:8].js'
const contenthash = isDev ? '[name].[hash:8].css' : '[name].[contenthash:8].css'

output: {
  path: path.resolve(__dirname, './dist'),
  filename: chunkhash,
  chunkFilename: chunkhash,
  publicPath: '/',
},
复制代码

4.各引かCSSの使用MiniCssExtractPluginのチャンクの生産

module: {
  rules: [
    {
      test: /\.(css|less)$/,
      use: {
        loader: isDev ? 'style-loader' : MiniCssExtractPlugin.loader
      },
    }
  ]
}
plugins: [
  new MiniCssExtractPlugin({
      filename: contenthash,
      chunkFilename: contenthash,
    }),
]
复制代码

5.独立したサードパーティ製のプラグ、永続キャッシュ

webpack.docschina.org/configurati...の $糸はuglifyjs-WebPACKの-プラグインを追加します

optimization: {
  runtimeChunk: {
    name: 'manifest',
  },
  splitChunks: {
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        chunks: 'all',
        name: 'vendor',
      },
    },
  },
  minimizer: [
    new UglifyJsPlugin({
      cache: true,
      parallel: true,
      sourceMap: true,
    }),
    new OptimizeCSSAssetsPlugin(),
  ],
},
复制代码

6.視覚分析BundleAnalyzerPlugin

// package.json
scripts: {
  "analyz": "NODE_ENV=production npm_config_report=true npm run build"
}

// webpack.config.json
plugins: [
  ...(process.env.npm_config_report ? [new BundleAnalyzerPlugin()] : []),
]
复制代码

速度最適化の3建設

1.文書検索要素狭い範囲

2.ダイナミックリンクライブラリDllPluginを生成します(サードパーティ製プラグインは一度だけコンパイル)

3.マルチコアCUPの使用は、変換ローダを促進HappyPackを使用します

WebPACKのビルドプロセスでは、最も時間のかかる変換ローダーあるファイルでのみシングルスレッド処理をJS、HappyPack原理は、複数のプロセスにタスク分解のこの部分で、ビルド時間を短縮します。

中規模のプロジェクトは、happypackの使用は、より高速な明白なビルドを確認してください。

// 见 git 记录"使用happypack"
复制代码

ParalleUglifyPlugin UglifyJS圧縮を加速を使用して4. CUP多核、。

new ParallelUglifyPlugin({
        uglifyJS: {
          output: {
            // 最紧凑输出
            beautify: false,
            // 删除所有注释
            comments: false,
          },
          compress: {
            drop_console: !isDev,
            collapse_vars: true,
            reduce_vars: true,
          },
        },
      }),
复制代码

4.書き込みローダー

webpack.docschina.org/contribute/...

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'vue-loader',
            options: {
              loaders: {
                // happy 不支持 vue-loader, 将js 交由 happypack
                js: 'happypack/loader?id=babel',
              },
            },
          },
          {
            // 为每个 vue 文件 添加 ~@/assets/less/variable.less, 避免人工每次导入。
            loader: 'less-auto-import-loader',
            options: {
              url: '~@/assets/less/variable.less',
            },
          },
        ],
      },
    ]
  }
  resolveLoader: {
    // 增加 loader 的查找范围
    modules: ['node_modules', './loaders/'],
  },
}

复制代码

5.書き込みプラグイン

*** ***焦点は、右のイベントが完了するポイントを見つけることです。コンパイラのフック

// EndWebpackPlugin webpack构建成功或失败后执行回调
class EndWebpackPlugin {
  constructor(doneCallback, failCallback) {
    this.doneCallback = doneCallback
    this.failCallback = failCallback
  }
  apply(compiler) {
    compiler.plugin('done', (stats) => {
      this.doneCallback(stats)
    })
    compiler.plugin('failed', (err) => {
      this.doneCallback(err)
    })
  }
}

// webpack.config.js
const EndWebpackPlugin = require('end-webpack-plugin');
plugins: [
  new EndWebpackPlugin((stats) => {}, (err) => {})
]
复制代码

githubの:github.com/lizhuang93/...
のWebPACK官网:webpack.docschina.org/concepts/

ます。https://juejin.im/post/5cefa7936fb9a07ef06f78baで再現

おすすめ

転載: blog.csdn.net/weixin_34319374/article/details/91476355