webpack之入门

2018-11-13  本文已影响15人  5df463a52098

一、简单的命令实现webpack打包

package.json通过一个命令将入口文件打包成指定的文件里。
1.全局安装webpack和webpack-cli
npm i webpack webpack-cli -g
2.新建一个项目, 然后初始化
npm init
然后会生成一个package.json和 package-lock.json
3.在项目本地安装webpack和webpack-cli
npm i webpack webpack-cli -D
注: -D是--save-dev的缩写,-S是--save的缩写
区别:-D是只在开发环境即dev中使用,项目发布以后就不会使用到,如babel,loader等;-S是在开发和正式环境都会用到,如jQery,Vue等。
package.json中添加:

"build": "webpack "
image.png

npm run build 之后报错:


image.png

创建src文件夹,在src创建入口文件index.js:

src/index.js
console.log('i am entry file')

修改package.json:

 "build": "webpack --mode production ./src/index.js --ouput ./dist/main.js"

npm run build之后dist文件夹多一个输出文件main.js.


image.png

二、简单的webpack文件配置

创建webpack.config.js文件并修改package.json:

"build": "webpack --config webpack.config.js"

webpack.config.js:

1、配置loader

webpack 自身只理解 JavaScript,loader 可以将所有类型的文件转换为 webpack 能够处理的有效模块。

在 webpack 的配置中 loader 有两个目标:

  1. test 属性,用于标识出应该被对应的 loader 进行转换的某个或某些文件。
  2. use 属性,表示进行转换时,应该使用哪个 loader。
const path = require('path');
module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
   module: {
        rules: [
            {test:/\.txt$/, use: 'raw-loader'}
        ]
    }
  }

2、配置plugins

loader 被用于转换某些类型的模块,而插件则可以用于执行范围更广的任务。插件的范围包括,从打包优化和压缩,一直到重新定义环境中的变量。插件接口功能极其强大,可以用来处理各种各样的任务。

const path = require('path')
const HtmlWebpackplugin = require('html-webpack-plugin') // npm安装
module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },
    plugins: [
        new HtmlWebpackplugin({template: 'index.html'})
    ],
    module: {
        rules: [
            {test:/\.txt$/, use: 'raw-loader'}
        ],
    }
};

webpack 提供许多开箱可用的插件

3、模式

mode的参数有development 和production 两个选择。

选项 描述
development 会将 process.env.NODE_ENV 的值设为 development。启用 NamedChunksPlugin 和 NamedModulesPlugin。
production 会将 process.env.NODE_ENV 的值设为 production。启用 FlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin 和 UglifyJsPlugin.
const path = require('path')
const HtmlWebpackplugin = require('html-webpack-plugin') // npm安装
module.exports = {
    mode: 'production',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },
    plugins: [
        new HtmlWebpackplugin({template: 'index.html'})
    ],
    module: {
        rules: [
            {test:/\.txt$/, use: 'raw-loader'}
        ],
    }
};

4、resolve解析

常见的resolve配置参数:
1、alias别名:创建 import 或 require 的别名,来确保模块引入变得更简单。
2、extensions:自动解析确定的扩展。

const path = require('path')
const HtmlWebpackplugin = require('html-webpack-plugin')
function resolve (dir) {
  return path.join(__dirname, '..', dir)
}
module.exports = {
    entry: {
        app: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "[name].js",
        publicPath: "/assets/"
    },
    resolve: {
        extensions: ['.js', 'json', '.vue'],
// 
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            '@': resolve('src')
        }
    },
    plugins: [
        new HtmlWebpackplugin({template: 'index.html'})
    ],
    module: {
        rules: [
            {test:/\.txt$/, use: 'raw-loader'}
        ],
    }
};

比如extensions:

extensions: [".js", ".json", ".vue"]

能够使用户在引入模块时不带扩展:

import https from './utils/https' // 引入utils目录下的https.js可以省略‘.js’扩展。

比如alias:

alias: {
  'vue$': 'vue/dist/vue.esm.js',
    '@': resolve('src')
}

能够使用户在引入模块时省略统一的目录前缀:

import template from '@/pages/template.vue' //引入/src/pages/template.vue可以省略统一的资源目录前缀src

npm run build打包成功

三、一个基础的vue应用

对上面的一步进行一些更高级的配置才能用于日常开发,以及生产环境。
1、热加载
npm install --save-dev webpack-dev-server

webpack.config.js

// 热加载
    devServer: {
        contentBase: './dist',
        hot: true
    }

package.json:

"start:dev": "webpack-dev-server --open"

npm run start:dev之后浏览器就开启热加载
2、加载css
npm install --save-dev style-loader css-loader

webpack.config.js

moudle: {
    rules: [
      {
        test: /\.css$/,
        use: [
          // loader 处理是从下往上构建的
          'style-loader',
          'css-loader'
        ]
      }
    ]
}

3、加载图片(字体)
npm insatll --save-dev file-loader

webpack.config.js:

moudle: {
    rules: [
     {
    test: /\.(png|svg|jpg|gif)$/,
     use: [
         'file-loader'
     ]
}
    ]
}

4、开发环境使用source map 便于调试
当webpack打包代码是,会把所有的源文件打包到一个bundle.js中,对于错误的定位不是很方便,为了更方便调试,webpack提供了source map功能
webpack.config.js:

devtool: 'inline-source-map', //'inline-source-map'、 'source-map'、'cheap-eval-source-map'

5、Vue单文件结构
npm install --save-dev vue-loader vue-template-compiler

webpack.config.js :

const vueLoaderPlugin = require('vue-loader/lib/plugin');
plugins: [
    new vueLoaderPlugin()
]

6、编译ES6代码,兼容老浏览器
npm install --save-dev babel-loader babel-core

webpack.config.js :

 moudle: {
        rules: [
            {
                test: /\.js$/,
                use: 'babel-loader'
            }
        ]
    },
第四步:
image.png

webpack.config.js:

const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
    mode: 'production',
    entry: {
        app: './src/main.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].min.js'
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title:'Vue-webpack',
            inject:'body',
            filename:'index.html',
            // template:path.resolve(__dirname, "index.html")
            template: './index.html'
        }),
        new VueLoaderPlugin()
    ],
    resolve: {
        alias: {
            'vue': 'vue/dist/vue.js'
        }
    },
    devServer: {
        // contentBase: './dist',
        contentBase: path.join(__dirname, 'dist'),
        compress: true, // 启用gzip压缩
        // hot: true,
        port: 8080
    },
    performance: {
        hints:false
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    // loader 处理是从下往上构建的
                    'style-loader',
                    'css-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.html$/,
                use: ['html-loader']
            },
            {
                test: /\.vue$/,
                use: ['vue-loader']
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    'file-loader'
                ]
            }
        ]
    },
    // devtool: 'inline-source-map', // 'source-map'、'cheap-eval-source-map'
}

main.js:

import  Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
    el: '#app',
    router,
    components: {App},
    template: '<App/>'
})

App.vue:

<template>
    <div id="app">
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: "App"
    }
</script>

<style scoped>

</style>

router/index.js:

import Vue from 'vue'
import Router from 'vue-router'
import index from '../components/index.vue'
Vue.use(Router)
export default new Router({
    routes: [
        {
            path: '/',
            name: 'index',
            component: index
        }
    ]
})

components/index.vue:

<template>
    <div>
        index
    </div>
</template>

<script>
    export default {
        name: "index"
    }
</script>

<style scoped>

</style>

npm run start:dev项目就启动起来了。
启动项目发生警告:


image.png

解决方法是:在webpack.config.js中加上:

performance: {
hints:false   
}

或者:

performance: {
    hints: "warning", // 枚举
    maxAssetSize: 30000000, // 整数类型(以字节为单位)
    maxEntrypointSize: 50000000, // 整数类型(以字节为单位)
    assetFilter: function(assetFilename) {
    // 提供资源文件名的断言函数
    return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
    
    }
}
上一篇 下一篇

猜你喜欢

热点阅读