美文网首页javascript
webpack入门第五集:配置开发生产环境,超级简单

webpack入门第五集:配置开发生产环境,超级简单

作者: 空气KQ | 来源:发表于2019-06-12 13:30 被阅读0次

    模块全部下载保存下来,方便教程创建demo5

    npm init -y
    npm install -y  webpack webpack-cli lodash  style-loader css-loader file-loader  csv-loader xml-loader  webpack-dev-server
    

    说白了就是配置多个文件而已,这里用到了合并的追加形式,单个文件也可以

    创建一个公用文件

    npm install --save-dev webpack-merge
    npm install --save-dev uglifyjs-webpack-plugin
    
    const path = require('path');
    const {CleanWebpackPlugin} = require('clean-webpack-plugin');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
        entry: {
            app: './src/index.js'
        },
        plugins: [
            new CleanWebpackPlugin(),
            new HtmlWebpackPlugin({
                title: 'Production'
            })
        ],
        output: {
            filename: '[name].bundle.js',
            path: path.resolve(__dirname, 'dist')
        }
    };
    

    开发环境dev

    const merge = require('webpack-merge');
    const common = require('./webpack.common.js');
        // 这里实现2个模块对象合并
         module.exports = merge(common, {
           devtool: 'inline-source-map',
           devServer: {
             contentBase: './dist'
           }
     });
    

    生产环境

    const merge = require('webpack-merge');
    const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
    const common = require('./webpack.common.js');
    module.exports = merge(common, {
        plugins: [
            new UglifyJSPlugin()
        ]
    });
    

    修改package.json

    {
      "name": "demo4",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "webpack-dev-server --open --config webpack.dev.js",
        "build": "webpack --config webpack.prod.js"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "css-loader": "^3.0.0",
        "csv-loader": "^3.0.2",
        "file-loader": "^4.0.0",
        "lodash": "^4.17.11",
        "style-loader": "^0.23.1",
        "webpack": "^4.33.0",
        "webpack-cli": "^3.3.4",
        "webpack-dev-server": "^3.7.1",
        "xml-loader": "^1.2.1"
      },
      "devDependencies": {
        "uglifyjs-webpack-plugin": "^2.1.3",
        "webpack-merge": "^4.2.1"
      }
    }
    
    

    执行

    npm run start 开发
    npm run build 生产
    

    相关文章

      网友评论

        本文标题:webpack入门第五集:配置开发生产环境,超级简单

        本文链接:https://www.haomeiwen.com/subject/noakfctx.html