├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .github └── FUNDING.yml ├── .gitignore ├── .postcssrc.js ├── README.md ├── build ├── build.js ├── check-versions.js ├── logo.png ├── utils.js ├── vue-loader.conf.js ├── webpack.base.conf.js ├── webpack.dev.conf.js └── webpack.prod.conf.js ├── config ├── dev.env.js ├── index.js ├── prod.env.js └── test.env.js ├── index.html ├── package-lock.json ├── package.json ├── src ├── App.vue ├── assets │ └── logo.png ├── components │ ├── TheLanguageSwitcher.vue │ └── TheNavigation.vue ├── constants │ └── trans.js ├── lang │ ├── bg.json │ └── en.json ├── main.js ├── pages │ ├── 404.vue │ ├── About.vue │ └── HelloWorld.vue ├── plugins │ ├── Translation.js │ └── i18n.js └── router │ ├── index.js │ └── routes.js ├── static └── .gitkeep └── test └── unit ├── .eslintrc ├── jest.conf.js ├── setup.js └── specs ├── components └── TheLanguageSwitcher.spec.js ├── pages └── HelloWorld.spec.js └── plugins └── Trans.spec.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { 4 | "modules": false 5 | }], 6 | "stage-2" 7 | ], 8 | "plugins": ["transform-runtime"], 9 | "env": { 10 | "test": { 11 | "presets": ["env", "stage-2"], 12 | "plugins": ["transform-es2015-modules-commonjs", "dynamic-import-node"] 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | /config/ 3 | /dist/ 4 | /*.js 5 | /test/unit/coverage/ 6 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // https://eslint.org/docs/user-guide/configuring 2 | 3 | module.exports = { 4 | root: true, 5 | parser: 'babel-eslint', 6 | parserOptions: { 7 | sourceType: 'module' 8 | }, 9 | env: { 10 | browser: true, 11 | }, 12 | globals: ['test'], 13 | // https://github.com/standard/standard/blob/master/docs/RULES-en.md 14 | extends: 'standard', 15 | // required to lint *.vue files 16 | plugins: [ 17 | 'html' 18 | ], 19 | // add your custom rules here 20 | 'rules': { 21 | // allow paren-less arrow functions 22 | 'arrow-parens': 0, 23 | // allow async-await 24 | 'generator-star-spacing': 0, 25 | // allow debugger during development 26 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 27 | 'one-var': 0 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: dobromir-hristov 4 | ko_fi: dobromir_hristov 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | /dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | /test/unit/coverage/ 8 | 9 | # Editor directories and files 10 | .idea 11 | .vscode 12 | *.suo 13 | *.ntvs* 14 | *.njsproj 15 | *.sln 16 | -------------------------------------------------------------------------------- /.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | // to edit target browsers: use "browserslist" field in package.json 6 | "postcss-import": {}, 7 | "autoprefixer": {} 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vue-i18n-starter 2 | 3 | > A Vue.js starter project for i18n websites 4 | 5 | ## Build Setup 6 | 7 | ``` bash 8 | # install dependencies 9 | npm install 10 | 11 | # serve with hot reload at localhost:8080 12 | npm run dev 13 | 14 | # build for production with minification 15 | npm run build 16 | 17 | # build for production and view the bundle analyzer report 18 | npm run build --report 19 | 20 | # run unit tests 21 | npm run unit 22 | 23 | # run all tests 24 | npm test 25 | 26 | # sync down lokalise translation strings. You need to create acc and generate token. Not available for free plan. 27 | npm run lokalise:down 28 | ``` 29 | 30 | ### Settings 31 | Default language, supported languages and fallback language can be setup inside [constants/trans.js](./src/constants/trans.js). 32 | 33 | Inside the [router/index.js](./src/router/index.js) the beforeEnter guard calls the `Trans.routeMiddleware`. That will redirect the user to a valid language route if the current one is not supported. 34 | 35 | -------------------------------------------------------------------------------- /build/build.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | require('./check-versions')() 3 | 4 | process.env.NODE_ENV = 'production' 5 | 6 | const ora = require('ora') 7 | const rm = require('rimraf') 8 | const path = require('path') 9 | const chalk = require('chalk') 10 | const webpack = require('webpack') 11 | const config = require('../config') 12 | const webpackConfig = require('./webpack.prod.conf') 13 | 14 | const spinner = ora('building for production...') 15 | spinner.start() 16 | 17 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 18 | if (err) throw err 19 | webpack(webpackConfig, function (err, stats) { 20 | spinner.stop() 21 | if (err) throw err 22 | process.stdout.write(stats.toString({ 23 | colors: true, 24 | modules: false, 25 | children: false, 26 | chunks: false, 27 | chunkModules: false 28 | }) + '\n\n') 29 | 30 | if (stats.hasErrors()) { 31 | console.log(chalk.red(' Build failed with errors.\n')) 32 | process.exit(1) 33 | } 34 | 35 | console.log(chalk.cyan(' Build complete.\n')) 36 | console.log(chalk.yellow( 37 | ' Tip: built files are meant to be served over an HTTP server.\n' + 38 | ' Opening index.html over file:// won\'t work.\n' 39 | )) 40 | }) 41 | }) 42 | -------------------------------------------------------------------------------- /build/check-versions.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const chalk = require('chalk') 3 | const semver = require('semver') 4 | const packageConfig = require('../package.json') 5 | const shell = require('shelljs') 6 | function exec (cmd) { 7 | return require('child_process').execSync(cmd).toString().trim() 8 | } 9 | 10 | const versionRequirements = [ 11 | { 12 | name: 'node', 13 | currentVersion: semver.clean(process.version), 14 | versionRequirement: packageConfig.engines.node 15 | } 16 | ] 17 | 18 | if (shell.which('npm')) { 19 | versionRequirements.push({ 20 | name: 'npm', 21 | currentVersion: exec('npm --version'), 22 | versionRequirement: packageConfig.engines.npm 23 | }) 24 | } 25 | 26 | module.exports = function () { 27 | const warnings = [] 28 | for (let i = 0; i < versionRequirements.length; i++) { 29 | const mod = versionRequirements[i] 30 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 31 | warnings.push(mod.name + ': ' + 32 | chalk.red(mod.currentVersion) + ' should be ' + 33 | chalk.green(mod.versionRequirement) 34 | ) 35 | } 36 | } 37 | 38 | if (warnings.length) { 39 | console.log('') 40 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 41 | console.log() 42 | for (let i = 0; i < warnings.length; i++) { 43 | const warning = warnings[i] 44 | console.log(' ' + warning) 45 | } 46 | console.log() 47 | process.exit(1) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /build/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dobromir-hristov/vue-i18n-starter/d389210674687794b8f8005dc8f6cd68e916e9b4/build/logo.png -------------------------------------------------------------------------------- /build/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const config = require('../config') 4 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 5 | const pkg = require('../package.json') 6 | 7 | exports.assetsPath = function (_path) { 8 | const assetsSubDirectory = process.env.NODE_ENV === 'production' 9 | ? config.build.assetsSubDirectory 10 | : config.dev.assetsSubDirectory 11 | return path.posix.join(assetsSubDirectory, _path) 12 | } 13 | 14 | exports.cssLoaders = function (options) { 15 | options = options || {} 16 | 17 | const cssLoader = { 18 | loader: 'css-loader', 19 | options: { 20 | sourceMap: options.sourceMap 21 | } 22 | } 23 | 24 | var postcssLoader = { 25 | loader: 'postcss-loader', 26 | options: { 27 | sourceMap: options.sourceMap 28 | } 29 | } 30 | 31 | // generate loader string to be used with extract text plugin 32 | function generateLoaders (loader, loaderOptions) { 33 | const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] 34 | if (loader) { 35 | loaders.push({ 36 | loader: loader + '-loader', 37 | options: Object.assign({}, loaderOptions, { 38 | sourceMap: options.sourceMap 39 | }) 40 | }) 41 | } 42 | 43 | // Extract CSS when that option is specified 44 | // (which is the case during production build) 45 | if (options.extract) { 46 | return ExtractTextPlugin.extract({ 47 | use: loaders, 48 | fallback: 'vue-style-loader' 49 | }) 50 | } else { 51 | return ['vue-style-loader'].concat(loaders) 52 | } 53 | } 54 | 55 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 56 | return { 57 | css: generateLoaders(), 58 | postcss: generateLoaders(), 59 | less: generateLoaders('less'), 60 | sass: generateLoaders('sass', { indentedSyntax: true }), 61 | scss: generateLoaders('sass'), 62 | stylus: generateLoaders('stylus'), 63 | styl: generateLoaders('stylus') 64 | } 65 | } 66 | 67 | // Generate loaders for standalone style files (outside of .vue) 68 | exports.styleLoaders = function (options) { 69 | const output = [] 70 | const loaders = exports.cssLoaders(options) 71 | for (const extension in loaders) { 72 | const loader = loaders[extension] 73 | output.push({ 74 | test: new RegExp('\\.' + extension + '$'), 75 | use: loader 76 | }) 77 | } 78 | return output 79 | } 80 | 81 | exports.createNotifierCallback = function () { 82 | const notifier = require('node-notifier') 83 | 84 | return (severity, errors) => { 85 | if (severity !== 'error') { 86 | return 87 | } 88 | const error = errors[0] 89 | 90 | const filename = error.file && error.file.split('!').pop() 91 | notifier.notify({ 92 | title: pkg.name, 93 | message: severity + ': ' + error.name, 94 | subtitle: filename || '', 95 | icon: path.join(__dirname, 'logo.png') 96 | }) 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const config = require('../config') 4 | const isProduction = process.env.NODE_ENV === 'production' 5 | const sourceMapEnabled = isProduction 6 | ? config.build.productionSourceMap 7 | : config.dev.cssSourceMap 8 | 9 | 10 | module.exports = { 11 | loaders: utils.cssLoaders({ 12 | sourceMap: sourceMapEnabled, 13 | extract: isProduction 14 | }), 15 | cssSourceMap: sourceMapEnabled, 16 | cacheBusting: config.dev.cacheBusting, 17 | transformToRequire: { 18 | video: 'src', 19 | source: 'src', 20 | img: 'src', 21 | image: 'xlink:href' 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const config = require('../config') 5 | const vueLoaderConfig = require('./vue-loader.conf') 6 | 7 | function resolve (dir) { 8 | return path.join(__dirname, '..', dir) 9 | } 10 | 11 | module.exports = { 12 | context: path.resolve(__dirname, '../'), 13 | entry: { 14 | app: './src/main.js' 15 | }, 16 | output: { 17 | path: config.build.assetsRoot, 18 | filename: '[name].js', 19 | publicPath: process.env.NODE_ENV === 'production' 20 | ? config.build.assetsPublicPath 21 | : config.dev.assetsPublicPath 22 | }, 23 | resolve: { 24 | extensions: ['.js', '.vue', '.json'], 25 | alias: { 26 | 'vue$': 'vue/dist/vue.esm.js', 27 | '@': resolve('src'), 28 | } 29 | }, 30 | module: { 31 | rules: [ 32 | ...(config.dev.useEslint? [{ 33 | test: /\.(js|vue)$/, 34 | loader: 'eslint-loader', 35 | enforce: 'pre', 36 | include: [resolve('src'), resolve('test')], 37 | options: { 38 | formatter: require('eslint-friendly-formatter'), 39 | emitWarning: !config.dev.showEslintErrorsInOverlay 40 | } 41 | }] : []), 42 | { 43 | test: /\.vue$/, 44 | loader: 'vue-loader', 45 | options: vueLoaderConfig 46 | }, 47 | { 48 | test: /\.js$/, 49 | loader: 'babel-loader', 50 | include: [resolve('src'), resolve('test')] 51 | }, 52 | { 53 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 54 | loader: 'url-loader', 55 | options: { 56 | limit: 10000, 57 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 58 | } 59 | }, 60 | { 61 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 62 | loader: 'url-loader', 63 | options: { 64 | limit: 10000, 65 | name: utils.assetsPath('media/[name].[hash:7].[ext]') 66 | } 67 | }, 68 | { 69 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 70 | loader: 'url-loader', 71 | options: { 72 | limit: 10000, 73 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 74 | } 75 | } 76 | ] 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const webpack = require('webpack') 4 | const config = require('../config') 5 | const merge = require('webpack-merge') 6 | const baseWebpackConfig = require('./webpack.base.conf') 7 | const HtmlWebpackPlugin = require('html-webpack-plugin') 8 | const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 9 | const portfinder = require('portfinder') 10 | 11 | const devWebpackConfig = merge(baseWebpackConfig, { 12 | module: { 13 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) 14 | }, 15 | // cheap-module-eval-source-map is faster for development 16 | devtool: config.dev.devtool, 17 | 18 | // these devServer options should be customized in /config/index.js 19 | devServer: { 20 | clientLogLevel: 'warning', 21 | historyApiFallback: true, 22 | hot: true, 23 | compress: true, 24 | host: process.env.HOST || config.dev.host, 25 | port: process.env.PORT || config.dev.port, 26 | open: config.dev.autoOpenBrowser, 27 | overlay: config.dev.errorOverlay ? { 28 | warnings: false, 29 | errors: true, 30 | } : false, 31 | publicPath: config.dev.assetsPublicPath, 32 | proxy: config.dev.proxyTable, 33 | quiet: true, // necessary for FriendlyErrorsPlugin 34 | watchOptions: { 35 | poll: config.dev.poll, 36 | } 37 | }, 38 | plugins: [ 39 | new webpack.DefinePlugin({ 40 | 'process.env': require('../config/dev.env') 41 | }), 42 | new webpack.HotModuleReplacementPlugin(), 43 | new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. 44 | new webpack.NoEmitOnErrorsPlugin(), 45 | // https://github.com/ampedandwired/html-webpack-plugin 46 | new HtmlWebpackPlugin({ 47 | filename: 'index.html', 48 | template: 'index.html', 49 | inject: true 50 | }), 51 | ] 52 | }) 53 | 54 | module.exports = new Promise((resolve, reject) => { 55 | portfinder.basePort = process.env.PORT || config.dev.port 56 | portfinder.getPort((err, port) => { 57 | if (err) { 58 | reject(err) 59 | } else { 60 | // publish the new Port, necessary for e2e tests 61 | process.env.PORT = port 62 | // add port to devServer config 63 | devWebpackConfig.devServer.port = port 64 | 65 | // Add FriendlyErrorsPlugin 66 | devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ 67 | compilationSuccessInfo: { 68 | messages: [`Your application is running here: http://${config.dev.host}:${port}`], 69 | }, 70 | onErrors: config.dev.notifyOnErrors 71 | ? utils.createNotifierCallback() 72 | : undefined 73 | })) 74 | 75 | resolve(devWebpackConfig) 76 | } 77 | }) 78 | }) 79 | -------------------------------------------------------------------------------- /build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const webpack = require('webpack') 5 | const config = require('../config') 6 | const merge = require('webpack-merge') 7 | const baseWebpackConfig = require('./webpack.base.conf') 8 | const CopyWebpackPlugin = require('copy-webpack-plugin') 9 | const HtmlWebpackPlugin = require('html-webpack-plugin') 10 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 11 | const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 12 | 13 | const env = process.env.NODE_ENV === 'testing' 14 | ? require('../config/test.env') 15 | : require('../config/prod.env') 16 | 17 | const webpackConfig = merge(baseWebpackConfig, { 18 | module: { 19 | rules: utils.styleLoaders({ 20 | sourceMap: config.build.productionSourceMap, 21 | extract: true, 22 | usePostCSS: true 23 | }) 24 | }, 25 | devtool: config.build.productionSourceMap ? config.build.devtool : false, 26 | output: { 27 | path: config.build.assetsRoot, 28 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 29 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 30 | }, 31 | plugins: [ 32 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 33 | new webpack.DefinePlugin({ 34 | 'process.env': env 35 | }), 36 | // UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify 37 | new webpack.optimize.UglifyJsPlugin({ 38 | compress: { 39 | warnings: false 40 | }, 41 | sourceMap: config.build.productionSourceMap, 42 | parallel: true 43 | }), 44 | // extract css into its own file 45 | new ExtractTextPlugin({ 46 | filename: utils.assetsPath('css/[name].[contenthash].css'), 47 | // set the following option to `true` if you want to extract CSS from 48 | // codesplit chunks into this main css file as well. 49 | // This will result in *all* of your app's CSS being loaded upfront. 50 | allChunks: false, 51 | }), 52 | // Compress extracted CSS. We are using this plugin so that possible 53 | // duplicated CSS from different components can be deduped. 54 | new OptimizeCSSPlugin({ 55 | cssProcessorOptions: config.build.productionSourceMap 56 | ? { safe: true, map: { inline: false } } 57 | : { safe: true } 58 | }), 59 | // generate dist index.html with correct asset hash for caching. 60 | // you can customize output by editing /index.html 61 | // see https://github.com/ampedandwired/html-webpack-plugin 62 | new HtmlWebpackPlugin({ 63 | filename: process.env.NODE_ENV === 'testing' 64 | ? 'index.html' 65 | : config.build.index, 66 | template: 'index.html', 67 | inject: true, 68 | minify: { 69 | removeComments: true, 70 | collapseWhitespace: true, 71 | removeAttributeQuotes: true 72 | // more options: 73 | // https://github.com/kangax/html-minifier#options-quick-reference 74 | }, 75 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 76 | chunksSortMode: 'dependency' 77 | }), 78 | // keep module.id stable when vender modules does not change 79 | new webpack.HashedModuleIdsPlugin(), 80 | // enable scope hoisting 81 | new webpack.optimize.ModuleConcatenationPlugin(), 82 | // split vendor js into its own file 83 | new webpack.optimize.CommonsChunkPlugin({ 84 | name: 'vendor', 85 | minChunks: function (module) { 86 | // any required modules inside node_modules are extracted to vendor 87 | return ( 88 | module.resource && 89 | /\.js$/.test(module.resource) && 90 | module.resource.indexOf( 91 | path.join(__dirname, '../node_modules') 92 | ) === 0 93 | ) 94 | } 95 | }), 96 | // extract webpack runtime and module manifest to its own file in order to 97 | // prevent vendor hash from being updated whenever app bundle is updated 98 | new webpack.optimize.CommonsChunkPlugin({ 99 | name: 'manifest', 100 | minChunks: Infinity 101 | }), 102 | // This instance extracts shared chunks from code splitted chunks and bundles them 103 | // in a separate chunk, similar to the vendor chunk 104 | // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk 105 | new webpack.optimize.CommonsChunkPlugin({ 106 | name: 'app', 107 | async: 'vendor-async', 108 | children: true, 109 | minChunks: 3 110 | }), 111 | 112 | // copy custom static assets 113 | new CopyWebpackPlugin([ 114 | { 115 | from: path.resolve(__dirname, '../static'), 116 | to: config.build.assetsSubDirectory, 117 | ignore: ['.*'] 118 | } 119 | ]) 120 | ] 121 | }) 122 | 123 | if (config.build.productionGzip) { 124 | const CompressionWebpackPlugin = require('compression-webpack-plugin') 125 | 126 | webpackConfig.plugins.push( 127 | new CompressionWebpackPlugin({ 128 | asset: '[path].gz[query]', 129 | algorithm: 'gzip', 130 | test: new RegExp( 131 | '\\.(' + 132 | config.build.productionGzipExtensions.join('|') + 133 | ')$' 134 | ), 135 | threshold: 10240, 136 | minRatio: 0.8 137 | }) 138 | ) 139 | } 140 | 141 | if (config.build.bundleAnalyzerReport) { 142 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 143 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 144 | } 145 | 146 | module.exports = webpackConfig 147 | -------------------------------------------------------------------------------- /config/dev.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const merge = require('webpack-merge') 3 | const prodEnv = require('./prod.env') 4 | 5 | module.exports = merge(prodEnv, { 6 | NODE_ENV: '"development"' 7 | }) 8 | -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | // Template version: 1.2.4 3 | // see http://vuejs-templates.github.io/webpack for documentation. 4 | 5 | const path = require('path') 6 | 7 | module.exports = { 8 | dev: { 9 | 10 | // Paths 11 | assetsSubDirectory: 'static', 12 | assetsPublicPath: '/', 13 | proxyTable: {}, 14 | 15 | // Various Dev Server settings 16 | host: 'localhost', // can be overwritten by process.env.HOST 17 | port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined 18 | autoOpenBrowser: false, 19 | errorOverlay: true, 20 | notifyOnErrors: true, 21 | poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- 22 | 23 | // Use Eslint Loader? 24 | // If true, your code will be linted during bundling and 25 | // linting errors and warnings will be shown in the console. 26 | useEslint: true, 27 | // If true, eslint errors and warnings will also be shown in the error overlay 28 | // in the browser. 29 | showEslintErrorsInOverlay: false, 30 | 31 | /** 32 | * Source Maps 33 | */ 34 | 35 | // https://webpack.js.org/configuration/devtool/#development 36 | devtool: 'eval-source-map', 37 | 38 | // If you have problems debugging vue-files in devtools, 39 | // set this to false - it *may* help 40 | // https://vue-loader.vuejs.org/en/options.html#cachebusting 41 | cacheBusting: true, 42 | 43 | // CSS Sourcemaps off by default because relative paths are "buggy" 44 | // with this option, according to the CSS-Loader README 45 | // (https://github.com/webpack/css-loader#sourcemaps) 46 | // In our experience, they generally work as expected, 47 | // just be aware of this issue when enabling this option. 48 | cssSourceMap: false, 49 | }, 50 | 51 | build: { 52 | // Template for index.html 53 | index: path.resolve(__dirname, '../dist/index.html'), 54 | 55 | // Paths 56 | assetsRoot: path.resolve(__dirname, '../dist'), 57 | assetsSubDirectory: 'static', 58 | assetsPublicPath: '/', 59 | 60 | /** 61 | * Source Maps 62 | */ 63 | 64 | productionSourceMap: true, 65 | // https://webpack.js.org/configuration/devtool/#production 66 | devtool: '#source-map', 67 | 68 | // Gzip off by default as many popular static hosts such as 69 | // Surge or Netlify already gzip all static assets for you. 70 | // Before setting to `true`, make sure to: 71 | // npm install --save-dev compression-webpack-plugin 72 | productionGzip: false, 73 | productionGzipExtensions: ['js', 'css'], 74 | 75 | // Run the build command with an extra argument to 76 | // View the bundle analyzer report after build finishes: 77 | // `npm run build --report` 78 | // Set to `true` or `false` to always turn it on or off 79 | bundleAnalyzerReport: process.env.npm_config_report 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /config/prod.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | module.exports = { 3 | NODE_ENV: '"production"' 4 | } 5 | -------------------------------------------------------------------------------- /config/test.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const merge = require('webpack-merge') 3 | const devEnv = require('./dev.env') 4 | 5 | module.exports = merge(devEnv, { 6 | NODE_ENV: '"testing"' 7 | }) 8 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | vue-i18n-starter 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-i18n-starter", 3 | "version": "1.0.0", 4 | "description": "A Vue.js starter project for i18n websites", 5 | "author": "Dobromir Hristov ", 6 | "private": true, 7 | "scripts": { 8 | "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", 9 | "start": "npm run dev", 10 | "unit": "jest --config test/unit/jest.conf.js --coverage", 11 | "test": "npm run unit", 12 | "test:watch": "jest --config test/unit/jest.conf.js --watch", 13 | "lint": "eslint --ext .js,.vue src test/unit/specs", 14 | "build": "node build/build.js", 15 | "lokalise:down": "lokalise --token=YOUR_TOKEN --project=PROJECT_ID --output=src/lang/" 16 | }, 17 | "dependencies": { 18 | "axios": "^0.17.1", 19 | "lokalise": "0.0.5", 20 | "vue": "^2.5.2", 21 | "vue-i18n": "^7.3.2", 22 | "vue-router": "^3.0.1", 23 | "vue-test-utils": "^1.0.0-beta.6" 24 | }, 25 | "devDependencies": { 26 | "autoprefixer": "^7.1.2", 27 | "babel-core": "^6.22.1", 28 | "babel-eslint": "^7.1.1", 29 | "babel-jest": "^21.0.2", 30 | "babel-loader": "^7.1.1", 31 | "babel-plugin-dynamic-import-node": "^1.2.0", 32 | "babel-plugin-module-resolver": "^3.0.0", 33 | "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", 34 | "babel-plugin-transform-runtime": "^6.22.0", 35 | "babel-preset-env": "^1.3.2", 36 | "babel-preset-stage-2": "^6.22.0", 37 | "babel-register": "^6.22.0", 38 | "chalk": "^2.0.1", 39 | "copy-webpack-plugin": "^4.0.1", 40 | "css-loader": "^0.28.0", 41 | "eslint": "^3.19.0", 42 | "eslint-config-standard": "^10.2.1", 43 | "eslint-friendly-formatter": "^3.0.0", 44 | "eslint-loader": "^1.7.1", 45 | "eslint-plugin-html": "^3.0.0", 46 | "eslint-plugin-import": "^2.7.0", 47 | "eslint-plugin-node": "^5.2.0", 48 | "eslint-plugin-promise": "^3.4.0", 49 | "eslint-plugin-standard": "^3.0.1", 50 | "eventsource-polyfill": "^0.9.6", 51 | "extract-text-webpack-plugin": "^3.0.0", 52 | "file-loader": "^1.1.4", 53 | "friendly-errors-webpack-plugin": "^1.6.1", 54 | "html-webpack-plugin": "^2.30.1", 55 | "jest": "^21.2.0", 56 | "jest-serializer-vue": "^0.3.0", 57 | "node-notifier": "^5.1.2", 58 | "optimize-css-assets-webpack-plugin": "^3.2.0", 59 | "ora": "^1.2.0", 60 | "portfinder": "^1.0.13", 61 | "postcss-import": "^11.0.0", 62 | "postcss-loader": "^2.0.8", 63 | "rimraf": "^2.6.0", 64 | "semver": "^5.3.0", 65 | "shelljs": "^0.7.6", 66 | "url-loader": "^0.5.8", 67 | "vue-jest": "^1.0.2", 68 | "vue-loader": "^13.3.0", 69 | "vue-style-loader": "^3.0.1", 70 | "vue-template-compiler": "^2.5.2", 71 | "webpack": "^3.6.0", 72 | "webpack-bundle-analyzer": "^2.9.0", 73 | "webpack-dev-server": "^2.9.1", 74 | "webpack-merge": "^4.1.0" 75 | }, 76 | "engines": { 77 | "node": ">= 4.0.0", 78 | "npm": ">= 3.0.0" 79 | }, 80 | "browserslist": [ 81 | "> 1%", 82 | "last 2 versions", 83 | "not ie <= 8" 84 | ] 85 | } 86 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 12 | 13 | 25 | 26 | 36 | -------------------------------------------------------------------------------- /src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dobromir-hristov/vue-i18n-starter/d389210674687794b8f8005dc8f6cd68e916e9b4/src/assets/logo.png -------------------------------------------------------------------------------- /src/components/TheLanguageSwitcher.vue: -------------------------------------------------------------------------------- 1 | 18 | 44 | 45 | 50 | -------------------------------------------------------------------------------- /src/components/TheNavigation.vue: -------------------------------------------------------------------------------- 1 | 11 | 12 | 30 | -------------------------------------------------------------------------------- /src/constants/trans.js: -------------------------------------------------------------------------------- 1 | export const DEFAULT_LANGUAGE = 'en' 2 | export const FALLBACK_LANGUAGE = 'en' 3 | export const SUPPORTED_LANGUAGES = ['en', 'bg'] 4 | -------------------------------------------------------------------------------- /src/lang/bg.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome_message": "Добре дошли във Вашият Vue.js App", 3 | "popular_links": "Популярни линкове", 4 | "ecosystem": "Екосистема", 5 | "pages": { 6 | "about": "Страница за нас" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/lang/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome_message": "Welcome to Your Vue.js App", 3 | "popular_links": "Popular Links", 4 | "ecosystem": "Ecosystem", 5 | "pages": { 6 | "about": "About Page" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | // The Vue build version to load with the `import` command 2 | // (runtime-only or standalone) has been set in webpack.base.conf with an alias. 3 | import Vue from 'vue' 4 | import App from './App' 5 | import router from './router' 6 | import { i18n } from '@/plugins/i18n' 7 | import { Trans } from './plugins/Translation' 8 | 9 | Vue.prototype.$i18nRoute = Trans.i18nRoute.bind(Trans) 10 | 11 | Vue.config.productionTip = false 12 | 13 | /* eslint-disable no-new */ 14 | new Vue({ 15 | el: '#app', 16 | router, 17 | i18n, 18 | render: (h) => h(App) 19 | }) 20 | -------------------------------------------------------------------------------- /src/pages/404.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /src/pages/About.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /src/pages/HelloWorld.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 21 | 22 | 23 | 46 | -------------------------------------------------------------------------------- /src/plugins/Translation.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import { SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE } from '@/constants/trans' 3 | import { i18n } from '@/plugins/i18n' 4 | 5 | const Trans = { 6 | get defaultLanguage () { 7 | return DEFAULT_LANGUAGE 8 | }, 9 | get supportedLanguages () { 10 | return SUPPORTED_LANGUAGES 11 | }, 12 | get currentLanguage () { 13 | return i18n.locale 14 | }, 15 | set currentLanguage (lang) { 16 | i18n.locale = lang 17 | }, 18 | /** 19 | * Gets the first supported language that matches the user's 20 | * @return {String} 21 | */ 22 | getUserSupportedLang () { 23 | const userPreferredLang = Trans.getUserLang() 24 | 25 | // Check if user preferred browser lang is supported 26 | if (Trans.isLangSupported(userPreferredLang.lang)) { 27 | return userPreferredLang.lang 28 | } 29 | // Check if user preferred lang without the ISO is supported 30 | if (Trans.isLangSupported(userPreferredLang.langNoISO)) { 31 | return userPreferredLang.langNoISO 32 | } 33 | return Trans.defaultLanguage 34 | }, 35 | /** 36 | * Returns the users preferred language 37 | */ 38 | getUserLang () { 39 | const lang = window.navigator.language || window.navigator.userLanguage || Trans.defaultLanguage 40 | return { 41 | lang: lang, 42 | langNoISO: lang.split('-')[0] 43 | } 44 | }, 45 | /** 46 | * Sets the language to various services (axios, the html tag etc) 47 | * @param {String} lang 48 | * @return {String} lang 49 | */ 50 | setI18nLanguageInServices (lang) { 51 | Trans.currentLanguage = lang 52 | axios.defaults.headers.common['Accept-Language'] = lang 53 | document.querySelector('html').setAttribute('lang', lang) 54 | return lang 55 | }, 56 | /** 57 | * Loads new translation messages and changes the language when finished 58 | * @param lang 59 | * @return {Promise} 60 | */ 61 | changeLanguage (lang) { 62 | if (!Trans.isLangSupported(lang)) return Promise.reject(new Error('Language not supported')) 63 | if (i18n.locale === lang) return Promise.resolve(lang) // has been loaded prior 64 | return Trans.loadLanguageFile(lang).then(msgs => { 65 | i18n.setLocaleMessage(lang, msgs.default || msgs) 66 | return Trans.setI18nLanguageInServices(lang) 67 | }) 68 | }, 69 | /** 70 | * Async loads a translation file 71 | * @param lang 72 | * @return {Promise<*>|*} 73 | */ 74 | loadLanguageFile (lang) { 75 | return import(/* webpackChunkName: "lang-[request]" */ `@/lang/${lang}.json`) 76 | }, 77 | /** 78 | * Checks if a lang is supported 79 | * @param {String} lang 80 | * @return {boolean} 81 | */ 82 | isLangSupported (lang) { 83 | return Trans.supportedLanguages.includes(lang) 84 | }, 85 | /** 86 | * Checks if the route's param is supported, if not, redirects to the first supported one. 87 | * @param {Route} to 88 | * @param {Route} from 89 | * @param {Function} next 90 | * @return {*} 91 | */ 92 | routeMiddleware (to, from, next) { 93 | // Load async message files here 94 | const lang = to.params.lang 95 | if (!Trans.isLangSupported(lang)) return next(Trans.getUserSupportedLang()) 96 | return Trans.changeLanguage(lang).then(() => next()) 97 | }, 98 | /** 99 | * Returns a new route object that has the current language already defined 100 | * To be used on pages and components, outside of the main \ route, like on Headers and Footers. 101 | * @example Click Me 102 | * @param {Object} to - route object to construct 103 | */ 104 | i18nRoute (to) { 105 | return { 106 | ...to, 107 | params: { lang: this.currentLanguage, ...to.params } 108 | } 109 | } 110 | } 111 | 112 | export { Trans } 113 | -------------------------------------------------------------------------------- /src/plugins/i18n.js: -------------------------------------------------------------------------------- 1 | import VueI18n from 'vue-i18n' 2 | import Vue from 'vue' 3 | import { DEFAULT_LANGUAGE, FALLBACK_LANGUAGE } from '@/constants/trans' 4 | import en from '@/lang/en.json' 5 | 6 | Vue.use(VueI18n) 7 | export const i18n = new VueI18n({ 8 | locale: DEFAULT_LANGUAGE, // set locale 9 | fallbackLocale: FALLBACK_LANGUAGE, 10 | messages: { en }// set locale messages 11 | }) 12 | -------------------------------------------------------------------------------- /src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Router from 'vue-router' 3 | import routes from './routes' 4 | Vue.use(Router) 5 | 6 | export default new Router({ 7 | routes, 8 | mode: 'history', 9 | base: __dirname, 10 | scrollBehavior (to, from, savedPosition) { 11 | if (savedPosition) { 12 | return savedPosition 13 | } 14 | 15 | return { x: 0, y: 0 } 16 | } 17 | }) 18 | -------------------------------------------------------------------------------- /src/router/routes.js: -------------------------------------------------------------------------------- 1 | import { Trans } from '@/plugins/Translation' 2 | 3 | function load (component) { 4 | // '@' is aliased to src/components 5 | return () => import(/* webpackChunkName: "[request]" */ `@/pages/${component}.vue`) 6 | } 7 | 8 | export default [ 9 | { 10 | path: '/:lang', 11 | component: { 12 | template: '' 13 | }, 14 | beforeEnter: Trans.routeMiddleware, 15 | children: [ 16 | { 17 | path: '', 18 | name: 'HelloWorld', 19 | component: load('HelloWorld') 20 | }, 21 | { 22 | path: 'about', 23 | name: 'about', 24 | component: load('About') 25 | }, 26 | { 27 | path: '*', 28 | component: load('404') 29 | } 30 | ] 31 | }, 32 | { 33 | // Redirect user to supported lang version. 34 | path: '*', 35 | redirect (to) { 36 | return Trans.getUserSupportedLang() 37 | } 38 | } 39 | ] 40 | -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dobromir-hristov/vue-i18n-starter/d389210674687794b8f8005dc8f6cd68e916e9b4/static/.gitkeep -------------------------------------------------------------------------------- /test/unit/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "jest": true 4 | }, 5 | "globals": { 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /test/unit/jest.conf.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | 3 | module.exports = { 4 | rootDir: path.resolve(__dirname, '../../'), 5 | moduleFileExtensions: [ 6 | 'js', 7 | 'json', 8 | 'vue' 9 | ], 10 | moduleNameMapper: { 11 | '^@/(.*)$': '/src/$1' 12 | }, 13 | transform: { 14 | '^.+\\.js$': '/node_modules/babel-jest', 15 | '.*\\.(vue)$': '/node_modules/vue-jest' 16 | }, 17 | snapshotSerializers: ['/node_modules/jest-serializer-vue'], 18 | setupFiles: ['/test/unit/setup'], 19 | mapCoverage: true, 20 | coverageDirectory: '/test/unit/coverage', 21 | collectCoverageFrom: [ 22 | 'src/**/*.{js,vue}', 23 | '!src/main.js', 24 | '!src/router/index.js', 25 | '!**/node_modules/**' 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /test/unit/setup.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | 3 | Vue.config.productionTip = false 4 | -------------------------------------------------------------------------------- /test/unit/specs/components/TheLanguageSwitcher.spec.js: -------------------------------------------------------------------------------- 1 | import TheLanguageSwitcher from '@/components/TheLanguageSwitcher.vue' 2 | import { i18n } from '@/plugins/i18n' 3 | import { mount } from 'vue-test-utils' 4 | import { SUPPORTED_LANGUAGES } from '@/constants/trans' 5 | import {Trans} from '@/plugins/Translation' 6 | 7 | describe('TheLanguageSwitcher.vue', () => { 8 | let wrapper 9 | beforeEach(() => { 10 | wrapper = mount(TheLanguageSwitcher, { i18n }) 11 | }) 12 | 13 | it('renders properly', () => { 14 | expect(wrapper.find('.LanguageSwitcher')).toBeTruthy() 15 | }) 16 | 17 | it('has the right amount of options to select', () => { 18 | const options = wrapper.findAll('.LanguageSwitcher option') 19 | expect(options).toHaveLength(SUPPORTED_LANGUAGES.length) 20 | }) 21 | 22 | it('sets the current language as current option', () => { 23 | const currentOption = wrapper.find('.LanguageSwitcher .is-selected') 24 | 25 | expect(currentOption.element.value).toBe(Trans.currentLanguage) 26 | }) 27 | 28 | it('checks that isCurrentLanguage checks if supplied language is current', () => { 29 | expect(wrapper.vm.isCurrentLanguage('bg')).toBeFalsy() 30 | expect(wrapper.vm.isCurrentLanguage('en')).toBeTruthy() 31 | }) 32 | 33 | it('calls changeLanguage when an option is clicked', async () => { 34 | const changeLanguageMethod = jest.fn() 35 | const changeLanguageTo = 'bg' 36 | wrapper.setMethods({ 37 | changeLanguage: changeLanguageMethod 38 | }) 39 | const option = wrapper.find('option[value="bg"]') 40 | 41 | option.trigger('change') 42 | 43 | expect(changeLanguageMethod).toHaveBeenCalled() 44 | }) 45 | }) 46 | -------------------------------------------------------------------------------- /test/unit/specs/pages/HelloWorld.spec.js: -------------------------------------------------------------------------------- 1 | import HelloWorld from '@/pages/HelloWorld' 2 | import { i18n } from '@/plugins/i18n' 3 | import { mount } from 'vue-test-utils' 4 | import {Trans} from '@/plugins/Translation' 5 | 6 | describe('HelloWorld.vue', () => { 7 | const vm = mount(HelloWorld, { i18n }) 8 | it('renders proper welcome message', () => { 9 | expect(vm.find('.hello h1').text()) 10 | .toEqual(i18n.t('welcome_message')) 11 | }) 12 | 13 | it('renders a proper popular links text', () => { 14 | expect(vm.find('.hello h2').text()) 15 | .toEqual(i18n.t('popular_links')) 16 | }) 17 | 18 | it('changes languages', async () => { 19 | await Trans.changeLanguage('bg') 20 | 21 | expect(i18n.locale).toBe('bg') 22 | 23 | expect(vm.find('.hello h1').text()) 24 | .toEqual(i18n.t('welcome_message')) 25 | }) 26 | }) 27 | -------------------------------------------------------------------------------- /test/unit/specs/plugins/Trans.spec.js: -------------------------------------------------------------------------------- 1 | let Trans = null 2 | let i18n = null 3 | const mockDefaultLanguage = 'en' 4 | const mockFallbackLanguage = 'en' 5 | const mockSupportedLanguages = ['en', 'de'] 6 | const mockApi = { 7 | service: { 8 | defaults: { 9 | headers: { 10 | common: {} 11 | } 12 | } 13 | } 14 | } 15 | /* Mock i18n instance */ 16 | jest.mock('@/plugins/i18n', () => { 17 | const mockedI18n = { 18 | locale: 'en', 19 | setLocaleMessage: jest.fn(function (locale, messages) { 20 | mockedI18n.locale = locale 21 | mockedI18n.messages[locale] = messages 22 | }), 23 | messages: {}, 24 | t: jest.fn(function (message, locale = mockedI18n.locale) { 25 | return mockedI18n.messages[locale][message] 26 | }) 27 | } 28 | return { i18n: mockedI18n } 29 | }) 30 | jest.mock('@/constants/trans', () => { 31 | return { 32 | DEFAULT_LANGUAGE: mockDefaultLanguage, 33 | FALLBACK_LANGUAGE: mockFallbackLanguage, 34 | SUPPORTED_LANGUAGES: mockSupportedLanguages 35 | } 36 | }) 37 | jest.mock('axios', () => mockApi) 38 | beforeEach(() => { 39 | Trans = require('@/plugins/Translation').Trans 40 | // stop service from loading Async files 41 | Trans.loadLanguageFile = jest.fn(() => Promise.resolve()) 42 | i18n = require('@/plugins/i18n').i18n 43 | }) 44 | 45 | afterEach(() => { 46 | jest.resetModules() 47 | }) 48 | 49 | let defineNavigatorLanguage = function (lang) { 50 | navigator.__defineGetter__('language', function () { 51 | return lang // customized user agent 52 | }) 53 | } 54 | describe('TranslationService', () => { 55 | it('should get default language', () => { 56 | expect(Trans.defaultLanguage).toEqual(mockDefaultLanguage) 57 | }) 58 | 59 | it('should return supported languages', () => { 60 | expect(Trans.supportedLanguages).toEqual(mockSupportedLanguages) 61 | }) 62 | 63 | it('should return the current language', () => { 64 | expect(Trans.currentLanguage).toEqual(i18n.locale) 65 | }) 66 | 67 | it('should set language in vue-i18n', () => { 68 | Trans.currentLanguage = 'bg' 69 | expect(i18n.locale).toEqual('bg') 70 | expect(i18n.locale).toEqual(Trans.currentLanguage) 71 | }) 72 | 73 | it('should return preferred language', () => { 74 | defineNavigatorLanguage('en-US') 75 | // global.navigator.language = 'en-US' 76 | expect(Trans.getUserLang()).toEqual({ 77 | lang: 'en-US', 78 | langNoISO: 'en' 79 | }) 80 | }) 81 | 82 | it('should return a supported language', () => { 83 | defineNavigatorLanguage('de') 84 | expect(Trans.getUserSupportedLang()).toBe('de') 85 | }) 86 | 87 | it('should return first supported language if actually supported', () => { 88 | jest.resetModules() 89 | jest.doMock('@/constants/trans', () => ({ 90 | SUPPORTED_LANGUAGES: ['bg-BG', 'bg', 'en'], 91 | DEFAULT_LANGUAGE: 'en', 92 | FALLBACK_LANGUAGE: 'en' 93 | })) 94 | Trans = require('@/services/TranslationService').Trans 95 | defineNavigatorLanguage('bg-BG') 96 | expect(Trans.getUserSupportedLang()).toBe('bg-BG') 97 | }) 98 | 99 | it('should test if a language is supported', () => { 100 | expect(Trans.isLangSupported('en')).toBeTruthy() 101 | }) 102 | 103 | it('should set language in services', () => { 104 | const setLanguage = Trans.setI18nLanguageInServices('en') 105 | const langHTMLTag = document.querySelector('html').getAttribute('lang') 106 | expect(setLanguage).toBe('en') 107 | expect(Trans.currentLanguage).toEqual(setLanguage) 108 | expect(mockApi.service.defaults.headers.common['Accept-Language']).toBe(setLanguage) 109 | expect(langHTMLTag).toBe(setLanguage) 110 | }) 111 | 112 | it('resolves if new lang is the same as the old one', async () => { 113 | expect(Trans.currentLanguage).toBe(mockDefaultLanguage) 114 | const newLang = 'en' 115 | const changedLang = await Trans.changeLanguage(newLang) 116 | expect(changedLang).toBe(newLang) 117 | }) 118 | 119 | it('rejects a promise if the new lang is not supported', async () => { 120 | const newLang = 'de' 121 | expect.assertions(1) 122 | try { 123 | await Trans.changeLanguage(newLang) 124 | } catch (error) { 125 | expect(error.message).toBe('Language not supported') 126 | } 127 | }) 128 | 129 | it('downloads new language messages and sets the current language', async () => { 130 | const newLang = 'bg' 131 | const mockedLanguageFile = { welcome_message: 'Welcome' } 132 | Trans.loadLanguageFile.mockImplementation(() => Promise.resolve(mockedLanguageFile)) 133 | const changedLang = await Trans.changeLanguage(newLang) 134 | expect(changedLang).toBe(newLang) 135 | expect(Trans.currentLanguage).toBe(newLang) 136 | expect(i18n.t('welcome_message')).toBe(mockedLanguageFile.welcome_message) 137 | }) 138 | }) 139 | --------------------------------------------------------------------------------