webpack手动搭建vue项目(二)—— 创建vue+elementui项目

1.安装依赖

> npm install vue vuex vue-router vue-resource element-ui --save-dev

> npm install babel-cli babel-core babel-loader babel-polyfill --save-dev

>npm install css-loader file-loader style-loader vue-loader node-sass sass-loader vue-template-compiler --save-dev

> npm install babel-preset-env babel-plugin-transform-object-rest-spread babel-plugin-syntax-dynamic-import --save-dev

>npm install clean-webpack-plugin copy-webpack-plugin uglifyjs-webpack-plugin extract-text-webpack-plugin --save-dev

如果为webpcak3.x:

npm install [email protected] [email protected] --save-dev

如果为webpack4.x:

1.需增加>npm install extract-text-webpack-plugin@next  core-js@3   --save-dev

2.上面的babel-cli babel-core babel-loader babel-polyfill  babel-preset-env babel-plugin-transform-object-rest-spread babel-plugin-syntax-dynamic-import需要变成:@babel/cli  @babel/core [email protected]  @babel/polyfill  @babel/preset-env  @babel/plugin-proposal-object-rest-spread  @babel/plugin-syntax-dynamic-import

2.构建项目目录

├── build/                      # webpack config files
│   |
|   |----webpack.base.js
|   |----webpack.dev.js
|   |----webpack.sit.js
|   |----webpack.prd.js
|
|
├── src/
│   ├── index.js                 # app entry file
│   ├── components/             # ui components
│   │   └── App.vue
|   |
│   └── asserts/                 # module assets (processed by webpack)
│   |   |
|   |   |----data/
|   |   |----images/
|   |---api/
|   |   |----api-path.js             存放项目接口路径
|   |----view
|   |    └── index.html         # index.html template
|   |
|   |---routes/                  #存放路由
|   |   |----index.js
|   |---store/
|   |   |----index.js           #参考https://vuex.vuejs.org/zh/guide/structure.html
|   |
|   |---js/
|   |   |---util.js             #一些公共方法
|   |
|   |---css/
|   |   |---index.css           #一些公共样式
|
├── .babelrc                    # babel config
├── package.json                # build scripts and dependencies
└── README.md                   # Default README file

3.添加.babelrc文件

{
	"presets": [
		["env", {
			"modules": false
		}]
	],
	"plugins": [
		"syntax-dynamic-import",
		"transform-object-rest-spread"
	]
}

如果为webpack4.x则

{
	"presets": [
		["@babel/preset-env", {
			"corejs": 3,
			"useBuiltIns": "usage"
		}]
	],
	"plugins": [
		"@babel/plugin-syntax-dynamic-import",
		"@babel/plugin-proposal-object-rest-spread"
	]
}

4.更改webpack.base配置

const path = require('path')
const extractTextPlugin = require('extract-text-webpack-plugin')
const htmlWebpackPlugin = require('html-webpack-plugin')
const copyWebpackPlugin = require('copy-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')  // 如果vue-loader 版本为15.x需要
module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname,'../dist'),
        filename: 'compiled/js/[name]-[hash:8].js',
        chunkFilename: 'compiled/js/[name]-[chunkhash:8].js'
    },
    module: {
        rules:[
            {
                test: /\.css$/,
                use: extractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader'
                })
            },
            {
                test: /\.(sass|scss)$/,
                use: extractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    extractCSS: true
                }
            },
            {
                test: /\.js$/,
                use: [
                    'babel-loader'
                ],
                exclude: /node_modules/
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif|bmp|woff|woff2|eot|ttf|otf)$/,
                use: [
                    'file-loader?outputPath=compiled/img/'
                ]
            }
        ]
    },
    resolve: {
        //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名
        extensions: ['.js', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, '../src'),
            '~': path.resolve(__dirname, '../src/components')
        }
    },
    plugins: [
        new VueLoaderPlugin(),  // 如果vue-router 版本为15.x需要
        new CleanWebpackPlugin(), //如果为插件版本较低则为(['dist'],{
            //root: path.resolve(__dirname, '../')
        //})   例如^0.1.19
        new copyWebpackPlugin([
			{ from: 'src/asserts'}
        ]),
        new extractTextPlugin({
            filename: '[name]-[hash:8].css',
            allChunks: true
        }),   //如果为webpack3则为 new extractTextPlugin('[name]-[hash:8].css'),
        new htmlWebpackPlugin({
            template: './src/view/index.html',
            hash: true
        })
    ]
}

5.增加sit和prd配置

//const webpack = require('webpack')
const merge = require('webpack-merge')
const uglifyJSPlugin = require('uglifyjs-webpack-plugin')
const common = require('./webpack.base')

module.exports = merge(common, {
    devtool: 'source-map',
    mode: 'development',  //webpack3.x不需要
    plugins: [
        new uglifyJSPlugin({
            sourceMap: true
		})
		// new webpack.DefinePlugin({
		// 	'process.env.Mock': false   //引入mock数据时,对单元测试有效
		// })
    ]
})
//const webpack = require('webpack')
const merge = require('webpack-merge')
const uglifyJSPlugin = require('uglifyjs-webpack-plugin')
const common = require('./webpack.base')

module.exports = merge(common, {
    mode:'production',  //webpack3.x不要
    plugins: [
        new uglifyJSPlugin(),
        new webpack.DefinePlugin({
			//'process.env.NODE_ENV': JSON.stringify('production')  // webpack3.x启用
			// 'process.env.Mock': false   // 引入mock时对单元测试有效
        })
    ]
})

增加脚本

"build_sit": "webpack --config build/webpack.sit.js",

"build_prd": "webpack --config build/webpack.prd.js"

6.总结

1.webpcak 4配置和webpack3配置有很多地方不一样,需要注意 :

webpack 3.x   babel-loader7.x   babel-core6.x

webpack 4.x    babel-loader8.x   @babel/core7.x

2.如果babel和babel-loader版本不一样的话会报错,此处为webpack3.x 所以babel-loader为7.1.1,babel-cli为6.26.0,babel-core为6.25.0

你可能感兴趣的:(vue,webpack)