webpack i18n国际化配置

先贴一张整体的结构图
webpack i18n国际化配置_第1张图片

整体思路是这样的:
首先在 webpack.config.js 配置所支持的全部语种,并为每个语种生成 boundle.js 文件;然后编写 resource 文件。最后在 index.html 文件中根据当前的语种引入相应的 boundle.js 文件。

package.json

{
  "name": "webpack1",
  "version": "1.0.0",
  "description": "This is just a test",
  "main": "dist/bundle.js",
  "scripts": {
    "test": "webpack-dev-server --open",
    "start": "webpack",
    "build": "webpack --config webpack.prod.js"
  },
  "keywords": [
    "webpack",
    "dev-server"
  ],
  "author": "slHuang",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4",
    "webpack-merge": "^4.1.1",
    "style-loader": "^0.19.0",
    "css-loader": "^0.28.7",
    "postcss-loader": "^2.0.8",
    "autoprefixer": "^7.1.6",
    "babel-core": "^6.26.0",
    "babel-cli": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-react": "^6.24.1",
    "babel-preset-env": "^1.6.1",
    "html-webpack-plugin": "^2.30.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "clean-webpack-plugin": "^0.1.17",
    "i18n-webpack-plugin": "^1.0.0",
    "html-loader": "^0.5.1",
    "file-loader": "^1.1.5",
    "eslint": "^4.11.0"
  },
  "dependencies": {
    "babel-runtime": "^6.26.0"
  }
}

webpack.config.js

const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");//根据模板html生成引入js后的html
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const I18nPlugin  = require("i18n-webpack-plugin");
const languages = { //添加支持的语种
    en: require("./resources/en.json"),
    cn: require("./resources/zh-cn.json")
};


module.exports = Object.keys(languages).map(function (language) {//为每个语种生成boundle文件
    return {
        name: language,
        devtool: "eval-source-map",
        entry: "./js/requireAddDiv.js",
        output: {
            path: __dirname + "/dist",
            filename: language + ".bundle.js"
        },
        devServer: {
            contentBase: "./",
            historyApiFallback: true,
            inline: true
        },
        module: {
            rules: [
                {
                    test: /(\.jsx|\.js)$/,
                    use: {
                        loader: "babel-loader?cacheDirectory=true",
                        options: {
                            presets: ["env", "react"],
                            plugins: ["transform-runtime"]
                        }
                    },
                    exclude: /node_modules/
                },
                /*{//这种方式只是解析 css,并不会分离 css
                    test: /\.css$/,
                    use: [
                        "style-loader",// 将 JS 字符串生成为 style 节点
                        {
                            loader: "css-loader",// 将 CSS 转化成 CommonJS 模块
                            options: {
                                module: true
                            }
                        },
                        {
                            loader: "postcss-loader",//可以自动添加前缀
                            options: {
                                plugins: function () {
                                    return [
                                        require("autoprefixer")
                                    ];
                                }
                            }
                        }
                    ]
                }*/
                {//分离css需要使用这样的形式
                    test: /\.css$/,
                    use: ExtractTextPlugin.extract({
                        fallback: "style-loader",
                        use: [
                            "css-loader",
                            {
                                loader: "postcss-loader",//可以自动添加前缀
                                options: {
                                    plugins: function () {
                                        return [
                                            require("autoprefixer")
                                        ];
                                    }
                                }
                            }
                        ]
                    })
                },
                {//处理图片,会在 output 目录中生成图片文件,js 中需要使用 require("*.jpg")先行引入才可以,同样 html 中通过 background-image 设置的图片不可以,但 css 中通过 background-image 设置的图片可以
                    test: /\.(jpg|png)$/,
                    use: {
                        loader: "file-loader",
                        options: {
                            outputPath: "images/",//这里的 images 貌似没什么作用,但不写不行,可以是任意的一个或多个字符
                            name: "[name].[hash:8].[ext]",//8表示截取 hash 的长度
                            useRelativePath: true//这个必须与 outputPath 结合使用才可以处理 css 中的引入的图片
                        }
                    }
                },
                {//处理 html 中通过 img 引入的图片,background-image 设置的图片不可以
                    test: /\.html$/,
                    use: "html-loader"
                }
            ]
        },
        plugins: [
            new webpack.BannerPlugin("版权所有,盗版必究!"),
            new HtmlWebpackPlugin({
                template: __dirname + "/index.temp.html"
            }),
            new webpack.optimize.OccurrenceOrderPlugin(),
            new webpack.optimize.UglifyJsPlugin({
                output: {
                    comments: false,  // remove all comments
                },
                compress: {
                    warnings: false
                }
            }),
            new ExtractTextPlugin("css/styles-[hash].css"),
            new I18nPlugin(languages[language])
        ]
    }
});

index.temp.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test webpacktitle>
    <script>
        var lang = navigator.language;
        var glbLang = "en";
        if (lang === "zh-CN") {
            glbLang = "cn";
        }
    script>
head>
<body>

    
    <div style="background-image: url(./images/A.jpg);width: 690px;height: 863px">div>

    <br style="color: red">

    
    <div class="imgs">div>

    <h3>This is my first test.h3>

    
    <img src="./images/A.jpg" alt="">

    <script>
        document.write('+'ipt src="'+glbLang+ '.bundle.js">+'ipt>');
    script>
body>
html>

en.json

{
  "label": "This is just a test"
}

zh-cn.json

{
  "label": "这是一个测试"
}

requireAddDiv.js

import val from "./variables";
import src from "../images/C.jpg";

require("../css/index.css");
const div = document.createElement("div");
div.innerHTML = val.values;
document.body.appendChild(div);
alert(__("label")); //使用 __ 引入 resource 文言


// 使用 js 添加图片
let img = document.createElement("img");
img.src = src;
let imgDiv = document.createElement("div");
imgDiv.appendChild(img);
document.body.appendChild(imgDiv);

variables.js

/**
 * Created by DreamCatcher on 2017/11/14.
 */
let val = {values: "This is my first div added!"};

export default val;

index.css

body {
    background-color: yellow;
    color: blue;
}
div.imgs {
    background-image: url(../images/B.jpg);
    width: 1333px;
    height: 1000px;
}

执行 npm run start

注意:若是使用了 HtmlWebpackPlugin 控件,会自动引入 boundle.js 文件,所以这种配置会在最终生成的 index.html 文件中引入两次 boundle.js 文件,手动将自动引入的 boundle.js 文件删除即可。

你可能感兴趣的:(webpack)