首页 > 语言 > JavaScript > 正文

使用webpack搭建vue项目及注意事项

2024-05-06 15:38:10
字体:
来源:转载
供稿:网友

有一句话叫“前人栽树后人乘凉”,还有一句话叫“如果说我看得比别人更远些,那是因为我站在巨人的肩膀上”。前一句是国人的俗语,后一句是那个发现了“万有引力”定律的牛顿说的。为什么要引用这两句呢?是因为我刚开始用vue的时候,使用的是vue-cli来搭建vue项目,快速又好用;我刚开始用react的时候,使用的是create-react-app来搭建react项目,方便又省事。使用这些已有的脚手架来搭建项目,无可厚非,对于新手来说,也确实能快速构建,不做置评。

既然已经有了这些现成的脚手架了,为什么我们还热衷于自己来配置webpack来搭建构建项目呢?因为我们只有了解并学会了配置webpack,我们才能更好地在打包构建项目时将webpack的性能发挥到极致,才能根据自身项目的实际需求,配置有利于项目开发的各种工具、插件,提高我们的开发效率。比如我们在打包项目时,可以分析哪些地方降低了webpack的打包速度,别人打包速度需要花去十多秒、二十多秒,而你能将打包的速度提升至几秒,这就是你的优势。当然,涉及到webpack的运行原理以及开发自己的loader或plugin就可以自行去学习了哈,本文只带你配置一个webpack来搭建一个vue项目。

wepack作为一个“模块打包机”其实是依赖了庞大的插件体系,插件体系是webpack的核心,可以说,webpack的生态就是建立在众多插件之上的,而开发环境和生产打包环境依赖的插件还是有所不同的,先以开发环境为例

webpack.config.js:

const path = require('path');const Webpack = require('webpack');const HtmlWebpackPlugin = require('html-webpack-plugin');const MiniCssExtractPlugin = require("mini-css-extract-plugin");const VueLoaderPlugin = require('vue-loader/lib/plugin');const ProgressBarPlugin = require('progress-bar-webpack-plugin');const resolve = (dir) => { return path.join(__dirname, '..', dir)}const assetsPath = (_path) => { return path.join('static', _path)}const isEnvProduction = process.env.NODE_ENV == "production", port = 3003;module.exports = { mode: 'development', devtool: 'source-map', entry: resolve('src'), output: {  path: resolve('dist'),  filename: isEnvProduction ? assetsPath('js/[name]-[hash].js') : '[name]-[hash].js',  chunkFilename: isEnvProduction ? assetsPath('js/[name]-[chunkhash:5].min.js') : '[name]-[chunkhash:5].min.js',  publicPath: '/', }, resolve: {  extensions: ['*', '.js', '.vue'], //webpack2.x extensions[0]不能为空 resolve属性中的extensions数组中用于配置程序可以自行补全哪些文件后缀  alias: {   '@': resolve('src'),   // 'vue$': 'vue/dist/vue.esm.js'  }, }, //提取公共代码 optimization: {  splitChunks: {   cacheGroups: {    commons: {     test: /[///]node_modules[///]/, //表示默认拆分node_modules中的模块     name: "vendor", //提取出来的文件命名     chunks: "all",  //提取所有文件的公共部分     minChunks: 2,   //表示提取公共部分最少的文件数 模块被引用>=2次,拆分至vendors公共模块     minSize: 0,   //表示提取公共部分最小的大小 模块超过0k自动被抽离成公共模块    },   }  } }, module: {  rules: [   {    test: //.vue$/,    use: ['vue-loader'],    exclude: /node_modules/,   },   {    test: //.js$/,    loader: 'babel-loader',    exclude: /node_modules/,    query: {     "presets": ["@babel/env"],     "plugins":      ["@babel/plugin-syntax-dynamic-import", "@babel/plugin-transform-runtime"],    }   },   {    test: //.(sa|sc|c)ss$/,    use: [     MiniCssExtractPlugin.loader,     'css-loader',     'postcss-loader',     'sass-loader',    ],   },   {    test: //.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,    use: 'file-loader?name=' + (isEnvProduction ? assetsPath('fonts/[name].[hash:8].[ext]') : 'fonts/[name].[hash:8].[ext]')   },   {    test: //.(jpg|jpeg|png|gif|ico|svg)$/,    loader: 'url-loader',    options: {     limit: 10000,     name: isEnvProduction ? assetsPath('images/[name].[hash:8].[ext]') : 'images/[name].[hash:8].[ext]',    }   },  ], }, plugins: [  new ProgressBarPlugin(),  new VueLoaderPlugin(),  //ProvidePlugin是webpack的内置模块,使用ProvidePlugin加载的模块在使用时将不再需要import和require进行引入  new Webpack.ProvidePlugin({   _: 'lodash',  }),  new HtmlWebpackPlugin({   template: './src/index.html', //文件路径及名称   filename: 'index.html',   //输出后的文件名称  }),  new MiniCssExtractPlugin({   filename: isEnvProduction ? assetsPath("css/[name]-[hash].css") : "css/[name]-[hash].css",   chunkFilename: isEnvProduction ? assetsPath("css/[name]-[hash].css") : "css/[name]-[hash].css", //默认就是取的以id或name为开头的css,所以可以加这行配置代码,也可以不加  }), ], devServer: {  port,  host: '0.0.0.0',  open: `http://localhost:${port}`,  stats: {   hash: false,   builtAt: false,   version: false,   modules: false,   children: false, ////解决类似Entrypoint undefined = index.html和Entrypoint mini-css-extract-plugin = *的警告   entrypoints: false,   colors: {    green: '/u001b[32m',    yellow: '/u001b[32m',   }  },  proxy: {   '/': {    target: '',    changeOrigin: true   }  },  inline: true,  compress: false,  disableHostCheck: true,  historyApiFallback: true, },}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选