手把手帶你搭建與配置Webpack + ES6 最新開發環境

在github創建新倉庫

github新建一個倉庫(項目地址webpack-es6-anyFrame
本地新建一個文件夾
在文件夾下執行

echo "# webpack-es6-anyFrame" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/xxxxxxx/webpack-es6-anyFrame.git
git push -u origin master

記得創建.gitignore文件

# dependencies
/node_modules

# production
/build

初始化項目

npm i -D webpack webpack-cli webpack-dev-server

安裝必要加載器

npm i -D autoprefixer style-loader css-loader sass node-sass sass-loader postcss-loader html-loader file-loader html-webpack-plugin uglifyjs-webpack-plugin mini-css-extract-plugin webpack-merge babel-plugin-import

創建postcss.config.js

module.exports = {
    plugins: [
        require('autoprefixer')
    ]
}

創建.browserslistrc

# Browsers that we support

defaults,
not ie < 9,
last 2 versions,
> 1%,
iOS 7,
last 
# 安裝bable解決在項目中使用ES6的問題

```handlebars
npm i -D babel-loader @babel/core @babel/preset-env  @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators

創建.babelrc

{
  "presets": [
      "@babel/preset-env",
  ],
  "plugins": ["@babel/transform-runtime", ["@babel/plugin-proposal-decorators", {"legacy": true}], "@babel/plugin-proposal-class-properties"]
}

開始構建項目基本架構

創建src文件,新建index.html及indes.js作爲項目入口

開始配置webpack

詳細解讀請移步
搭建初步的webpack腳手架
webpack—配置Sass、Less、PostCSS及加載樣式文件的多種方式

  • 創建webpack.common.config
    //webpack.common.config.js
    const path = require("path");
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    const paths = {
    src: path.resolve(__dirname, "src"),
    dist: path.resolve(__dirname, "dist"),
    };
    
    const evn = process.argv.pop();//獲取當前的環境,生產或開發
    const EVN = {
    pro: "production",
    dev: "development"
    };
    
    module.exports = {
    entry: [
        path.join(paths.src, "index.html"),
        // "@babel/polyfill",
        path.join(paths.src, "index.js"),
    ],
    output: {
        path: paths.dist,
        chunkFilename: evn === EVN.dev ? "[name].[hash].js" : "[name].js",
        filename: evn === EVN.dev ? "[name].[hash].js" : "[name].js",
    },
    module: {
        rules: [
        {
            //處理jsx及js
            test: /\.(jsx?)$/,
            use: {
            loader: "babel-loader",
            options: {
                cacheDirectory: evn === EVN.dev,
                sourceMap: evn === EVN.dev,
            },
            }
        },
        {
            ///處理html
            test: /\.html?/,
            exclude: /node_modules/,
            include: path.resolve(__dirname, "src"),
            use: {
            loader: "html-loader",
            options: {
                minimize: evn === EVN.dev,  //壓縮html代碼
                sourceMap: evn === EVN.dev  //生產環境可以不用資源映射
            }
            }
        },
        {// 規則數組
            test: /\.css|scss|less$/,
            use: ['style-loader', 'css-loader', 'sass-loader', 'postcss-loader'],
        },
          {
            test: /\.jpge|jpg|png|svg$/,
            loader: 'file-loader',
            query: {
              name: 'static/[name].[hash:8].[ext]'
            }
          }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
        template: path.join(paths.src, "index.html"),
        filename: "index.html",
        title: "react"
        }),
        new MiniCssExtractPlugin({
        filename: evn === EVN.dev ? "[name].[hash].css" : "[name].css",
        chunkFilename: evn === EVN.dev ? "[id].[hash].css" : "[id].css"
        }),
    ],
    resolve: {
        extensions: ['.js', '.json', '.jsx'],
        alias: {
        'react-native': 'react-native-web'
        }
    }
    };
    
  • 創建webpack.dev.config.js
    //webpack.dev.config.js
    const common = require("./webpack.common.config");
    const {resolve, join} = require("path");
    const merge = require("webpack-merge");
    const webpack = require("webpack");
    
    module.exports = merge(common, {   //合併兩個webpack文件
    devServer: {
        port: 8000,
        contentBase: join(__dirname, "dist"),
        compress: true,  // 對所有的服務器資源採用gzip壓縮
        hot: true,                     //模塊熱加載
        inline: true,
        open: 'Chrome',                //構建完成時自動打開瀏覽器
        openPage: "",
        stats: "errors-only" // 只打印錯誤
    },
    devtool: "inline-source-map",      //方便調試,將src目錄下的資源映射到瀏覽器中
    mode: "development",
    plugins: [
        new webpack.HotModuleReplacementPlugin(), //使用模塊熱加載插件
    ]
    });
    
  • 創建webpack.config.js
    const common = require("./webpack.common.config");
    const merge = require("webpack-merge");
    module.exports = merge(common, {
    devtool: "none",
    mode:"production"
    });
    

配置啓動命令

//package.son
{
    ···
    "scripts": {
        "start": "node_modules/.bin/webpack",
        "dev": "node_modules/.bin/webpack-dev-server  --config ./webpack.dev.config.js --process  --color --host localhost --mode development"
    },
    ···
}

簡單的使用

  • 在src下創建style.scss

    body{
        background: skyblue;
    }
    
  • 在src/index.js中導入樣式文件並編寫ES6代碼

    import './style.scss';
    {
        let a = 'hi~';
        alert(a);
    }
    

效果感人~

在這裏插入圖片描述
IE9的表現
在這裏插入圖片描述
項目地址webpack-es6-anyFrame

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章