Coder Social home page Coder Social logo

intlify / vue-i18n-loader Goto Github PK

View Code? Open in Web Editor NEW
268.0 7.0 29.0 1.63 MB

:globe_with_meridians: vue-i18n loader for custom blocks

License: MIT License

JavaScript 32.78% TypeScript 65.95% Vue 0.65% HTML 0.61%
vue vue-loader vue-i18n i18n loader webpack custom-blocks single-file-component

vue-i18n-loader's Introduction

Vue I18n Loader logo

@intlify/vue-i18n-loader

Build Status npm

webpack loader for Vue I18n


⚠️ Notice

This package is maintained for Vue I18n v8 (Vue 2).

If you want to use Vue I18n v9 (Vue 3) or later, See the @intlify/bundle-tools repo.

💿 Installation

$ npm i --save-dev @intlify/vue-i18n-loader

🚀 Usage

the below example thatApp.vue have i18n custom block:

Basic

<template>
  <p>{{ $t('hello') }}</p>
</template>

<script>
export default {
  name: 'app',
  // ...
}
</script>

<i18n>
{
  "en": {
    "hello": "hello world!"
  },
  "ja": {
    "hello": "こんにちは、世界!"
  }
}
</i18n>

The locale messages defined at i18n custom blocks are json format default.

Source importing

you also can:

<i18n src="./myLang.json"></i18n>
// ./myLnag.json
{
  "en": {
    "hello": "hello world!"
  },
  "ja": {
    "hello": "こんにちは、世界!"
  }
}

Locale definition

You can define locale messages for each locale with locale attr in single-file components:

<i18n locale="en">
{
  "hello": "hello world!"
}
</i18n>

<i18n locale="ja">
{
  "hello": "こんにちは、世界!"
}
</i18n>

The above defines two locales, which are merged at target single-file components.

Locale Messages formatting

Besides json format, You can be used by specifying the following format in the lang attribute:

  • yaml
  • json5

example yaml foramt:

<i18n locale="en" lang="yaml">
  hello: "hello world!"
</i18n>

<i18n locale="ja" lang="yml">
  hello: "こんにちは、世界!"
</i18n>

example json5 format:

<i18n lang="json5">
{
  "en": {
    // comments
    "hello": "hello world!"
  }
}
</i18n>

JavaScript

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import App from './App.vue'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en',
  messages: {
    en: {
      // ...
    },
    ja: {
      // ...
    }
  }
})
new Vue({
  i18n,
  render: h => h(App)
}).$mount('#app')

Webpack Config

vue-loader (v15 or later):

// for vue.config.js (Vue CLI)
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('i18n')
      .resourceQuery(/blockType=i18n/)
      .type('javascript/auto')
      .use('i18n')
      .loader('@intlify/vue-i18n-loader')
  }
}

vue-loader (v15 or later):

// for webpack.config.js (Without Vue CLI)
module.exports = {
  module: {
    rules: [
      {
        resourceQuery: /blockType=i18n/,
        type: 'javascript/auto',
        loader: '@intlify/vue-i18n-loader',
      },
    ]
  }
}

vue-loader (~v14.x):

// for webpack config file
module.exports = {
  module: {
    rules: [{
      test: /\.vue$/,
      loader: 'vue',
      options: {
        loaders: {
          i18n: '@intlify/vue-i18n-loader'
        }
      }
    }]
  }
}

📜 Changelog

Details changes for each release are documented in the CHANGELOG.md.

💪 Contribution

Please make sure to read the Contributing Guide before making a pull request.

©️ License

MIT

vue-i18n-loader's People

Contributors

aggre avatar chiaweilee avatar cslee avatar dependabot-preview[bot] avatar dhritzkiv avatar half2me avatar kazupon avatar lc-soft avatar nblackburn avatar neopren avatar renovate-bot avatar renovate[bot] avatar stephangerbeth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-i18n-loader's Issues

Support "lang" attr for i18n tag

I am working on a vscode extension for vue-i18n called vue-i18n-ally and trying to add support for SFC.

The current approach for YAML support in the document is not ideal for static analyze. Would it be possible to add support for lang attr just like script in SFC (which can also support more preprocessors)?

For example:

<i18n lang='yaml'>
en:
  hello: Hello World
</i18n>

<i18n lang='json5'>
{
  // comments
  ja: {
    hello: 'こんにちは、世界!',
  }
}
</i18n>

This issue is relative to #10, #31 and conflicted with #11

Single-file-components with vue-loader@15

I can't get vue-i18n-loader working together with vue-loader@15 for single-file-components. I created a minimal example repository here: https://github.com/mekeor/webpack4-vue2-vueLoader15-vueI18n-vueI18nLoader-singleFileComponent

Here are some snippets:

This is the entry-point for webpack:

'use strict';

import MainComponent from './MainComponent';

import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

const i18n = new VueI18n({
  locale: 'en',
});

/* eslint-disable no-new */

new Vue({
  i18n,
  el: '#mount-point',
  render: h => h(MainComponent),
});

This is the common webpack configuration:

'use strict';

const Path = require('path');

const CopyWebpackPlugin = require('copy-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
  entry: {
    'main': './source/main.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader',
        ],
      },
      {
        test: /\.js$/,
        include: [ './source' ],
        loader: 'babel-loader',
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.i18n$/,
        loader: 'vue-i18n-loader',
        type: 'javascript/auto',
      },
    ],
  },
  output: {
    filename: '[name].js',
    path: Path.resolve(__dirname, '../../target'),
    publicPath: '/',
  },
  plugins: [
    new VueLoaderPlugin(),
    new CopyWebpackPlugin([{
      test: /\.html$/,
      from: Path.resolve(__dirname, '../../source'),
      to: Path.resolve(__dirname, '../../target'),
    }]),
  ],
  resolve: {
    extensions: ['*', '.js', '.vue', ],
  },
};

The main component:

<template>
  <div class="mainComponent">
    <h1>{{ $t('hello') }}</h1>
  </div>
</template>

<script>
  'use strict';
  export default {
    name: 'mainComponent',
  };
</script>

<i18n>
  {
    "en": {
      "hello": "hello world!"
    },
    "ja": {
      "hello": "こんにちは、世界!"
    },
  }
</i18n>

This all results in this error:

Cannot translate the value of keypath 'hello'. Use the value of keypath as default.

Thus, the website just shows "hello" instead of "hello world!". Why?

index.ts not updated

9 days ago you released a new version that provides support for the "lang" attribute. Unfortunately you only updated the src/index.ts here. In lib/index.js the new code is missing completely. It would be great if you could update it as soon as possible. Thank you.

Failed to load .yaml using webpack (filetype not detected)

I'm trying to import yml file using vue-i18n-loader, but it tries to load it like json, and fails.

I'm using webpack-4, with following config from readme:

        {
          test: /\.(json5?|ya?ml)$/, // target json, json5, yaml and yml files
          type: "javascript/auto",
          loader: "@intlify/vue-i18n-loader",
          include: [ // Use `Rule.include` to specify the files of locale messages to be pre-compiled
            path.resolve(__dirname, "locale"),
          ],
        },

When i try to import yml file, like this:

import ru from "@locale/ru/example.yml";

If fails with following message:

SyntaxError: Unexpected token i in JSON at position 1
    at JSON.parse (<anonymous>)
    at generateCode (/home/serg/Projects/example/node_modules/@intlify/vue-i18n-loader/lib/index.js:29:22)
    at Object.loader (/home/serg/Projects/example/node_modules/@intlify/vue-i18n-loader/lib/index.js:13:55)

I used debugger to figure out what is happening, and problem is in this.resourceQuery, it's empty string. So yml is treatead as json.

Here is minimal reproduction: https://github.com/last-partizan/vue-i18n-loader-bug

Is there error in my configuration, or is this really a bug?

Support JSON and YAML Files at the same time

I don't know if it's possible, but it would be good if it were possible.

I already tried as mentioned in the docs something like this:

// Vue CLI 3.0
module.exports = {
  chainWebpack: config => {
    config.module
      .rule("i18n")
      .resourceQuery(/blockType=i18n/)
      .type('javascript/auto')
      .use("i18n")
        .loader("@kazupon/vue-i18n-loader")
        .end()
      .use('yaml')
        .loader('yaml-loader')
        .end()
  }
}

but doesn't work.

📢 Notice: transfer of repository

vue-i18n-loader will soon be transferred to intlify organaization. After that, it will be developed and maintained on intlify.

The @kazupon/vue-i18n-loader that has been released on npm will be released as @intlify/vue-i18n-loader in near future.

Intlify is a new i18n project kickoff by @kazupon. 😉

Hot-module-replacement support

Hello,

Is it possible to properly HMR <i18n> tags?
It doesn't work for me.

HMR does work properly for my .vue files (it correctly picks up changes from templates/scripts..).
It does see changes coming from <i18n> tags and I do see HMR output in console. Problem is, it doesn't pick up the changes.

I'm using webpack.HotModuleReplacementPlugin, and webpackDevServer with { hot: true } option

Is it just not implemented, or do I have to do some additional setup to make it work?

Thanks!

PS. Thanks for the good work with this loader and vue-i18n. I really like it!

Component based translations

Is it possible to refer to external JSON in order to translate a component, like:

inside a Component.vue

<i18n src="http://external.com/about.json"></i18n>

can this

hello,can this loader use in weex project.I found that vue-i18n can use in weex ,but @intlify-i18n-loader can not performace correctly in weex project,weex use "weex-loader",why?

Warning is not logged for HTML in i18n custom block

Using the latest version of vue (2.6.11), vue-i18n (8.21.0), and vue-i18n-loader (1.0.0), I think I'm seeing that single file component i18n custom blocks do not use the warnHtmlInMessage property set on the root VueI18n instance.

To reproduce, run npm run serve in the following repository:

https://github.com/matthew-white/vue-i18n-repro

Because a message in the HelloWorld component contains HTML, I would expect to see a warning logged to the console. However, I do not see a warning.

If warnHtmlInMessage is not specified when creating a VueI18n instance, then instead of defaulting warnHtmlInMessage to 'off', I think it would be great if it fell back to the property in the root VueI18n instance.

I'm not sure whether this issue belongs here or in https://github.com/kazupon/vue-i18n. However, because it relates to i18n custom blocks, I thought I'd file it here.

Parcel Support

I'm not sure if this is the right place to ask, but I'm interested in using <i18n> custom blocks in SFCs built with Parcel. I'm not terribly familiar with how that might work but I was wondering if that was on your radar yet or you might be able to add support?

Thanks!

Inconsistencies between i18n tag and messages object

Hey @kazupon,

I think I stumbled upon something. I have this strange unexpected behaviour where the index of an array item is not always of type number. I created a reproduction repository for you to check out:

  1. git clone [email protected]:mzdr/vue-i18n-loader-array-index-issue.git
  2. cd vue-i18n-loader-array-index-issue
  3. npm install
  4. npm run serve

As you see I have defined 2 arrays. One in App.vue and one in main.js. The way they are defined is identical, just the values differ. But if I loop over the arrays in App.vue the index keys of the i18n array are of type string, where the index keys from the messages array of the configuration object are of type number.

I am expecting that both array keys will be of the same type if defined identically, no matter if they are defined in the i18n block or within the actual i18n configuration.

This looks like a bug to me, can you please elaborate? Thanks!

v0.6.0 is missing code

Hi, I tried this:

cd
mkdir ohno
cd ohno
npm i @intlify/vue-i18n-loader
node -e 'require("@intlify/vue-i18n-loader")'

This was the result:

internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module '@intlify/vue-i18n-loader'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at [eval]:1:1
    at Script.runInThisContext (vm.js:122:20)
    at Object.runInThisContext (vm.js:329:38)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at evalScript (internal/bootstrap/node.js:590:27)

This makes sense when you look at the list of files, and notice it doesn't include any code:

$ ls node_modules/@intlify/vue-i18n-loader
CHANGELOG.md  LICENSE  package.json  README.md

To make matters worse, v0.6.0 is the only version published on npm, and trying to install by using something like this in your package.json will also fail:

"@intlify/vue-i18n-loader": "intlify/vue-i18n-loader"

Instead, if you're like me and want to install this package, you'll need to put this in your package.json:

"@intlify/vue-i18n-loader": "intlify/vue-i18n-loader#v0.5.0"

Usage with pug

Hey and thanks for an awesome plugin!

Is it possible to write pug code inside <i18n lang="yaml"> blocks? I have some Nuxt pages consisting of localised text mixed with markup, the latter being different between locales. Currently all my templates are written in pug and I'd like to leave it this way. How do I configure the plugin and webpack to convert pug code within yaml blocks to html before passing it to v-html?

Or perhaps I'm doing it the wrong way and I should look towards creating a separate Nuxt page for each locale?

YAML loader gives error on translation attempt

Error in mounted hook (Promise/async): "TypeError: last is null"

TypeError: "last is null"
    getPathValue vue-i18n.esm.js:1080
    _interpolate vue-i18n.esm.js:1384
    _translate vue-i18n.esm.js:1622
    _t vue-i18n.esm.js:1643
    $t vue-i18n.esm.js:192
    menu Header.vue:98
    VueJS 3
    header Header.vue:91
    VueJS 3
    drawHeader Header.vue:52
    _callee$ Header.vue:35
    tryCatch runtime.js:45
    invoke runtime.js:271
    method runtime.js:97
    node_modules asyncToGenerator.js:12
    node_modules asyncToGenerator.js:34
    node_modules asyncToGenerator.js:41
    node_modules asyncToGenerator.js:30
    mounted Header.vue:28
    VueJS 12
        invokeWithErrorHandling
        callHook
        insert
        invokeInsertHook
        patch
        _update
        updateComponent
        get
        run
        flushSchedulerQueue
        nextTick
        flushCallbacks
vue.runtime.esm.js:1888
    VueJS 4

My component:

<template>
<div> {{ $t("navbar.home") }} </div>
</template>
<i18n locale="en" lang="yaml">
navbar:
	home: "Home"
	projects: "Projects"
	employees: "Employees"
	admin: "Admin"
	admin_group:
		users: "Users"
</i18n>

My vue.config.js:

module.exports = {
	configureWebpack: {
		module: {
			rules: [
				{
					resourceQuery: /blockType=i18n/,
					type: "javascript/auto",
					loader: "@intlify/vue-i18n-loader",
				},
			],
		},
    }
}

Are there any breaking changes in v1.0.0?

The version has jumped from 0.6.x to 1.0.0. Does that mean that the package is now considered stable or there are major changes since 0.6.x?

I feel like I know the answer by looking at the code but I'd like to have confirmation.

I18n cannot respond to language changed in children components

Reporting a bug?

For projects created by vue-cli4, internationalization is supported using Vue add I18N. When the children component and parent component contain SFC I18N tags at the same time, the language of the children component cannot be correctly switched to the current language when switching the language in the parent component

Expected behavior

When switching languages, subcomponents can correctly respond to language changes

Reproduction

Detail and reappear
Vue-cli:
version: @vue/cli 4.5.13

Step:
1、Vue create i18n-demo
2、vue add i18n
Options:

📦 Installing vue-cli-plugin-i18n...

91 packages are looking for funding
run npm fund for details

✔ Successfully installed plugin: vue-cli-plugin-i18n
? The locale of project localization. en
? The fallback locale of project localization. en
? The directory where store localization messages of project. It's stored under src directory. locales
? Enable locale messages in Single file components ? Yes

🚀 Invoking generator for vue-cli-plugin-i18n...

Vue.config.js:
module.exports = {
pluginOptions: {
i18n: {
locale: "en",
fallbackLocale: "en",
localeDir: "locales",
enableInSFC: true,
},
},
};
parent compoent:

Vue logo
{{ $t("lang") }}
<script> // @ is an alias to /src import HelloI18n from '@/components/HelloI18n.vue' export default { name: 'Home', components: { HelloI18n, }, methods: { handler() { this.$i18n.locale = this.$i18n.locale == 'en' ? 'ja' : 'en' }, }, } </script> { "en": { "lang":"change language", "about": "about" }, "ja": { "lang":"言語を切り替え", "about": "について" } }

children component:

{{ $t("hello") }}

<script> export default { name: "HelloI18n", }; </script> { "en": { "hello": "Hello i18n in SFC!" }, "ja": { "hello": "こんにちは、i18n in SFC!" } }

System Info

node:v14.17.3
vue-cli: @vue/cli 4.5.13

Screenshot

image

Additional context

No response

Validations

  • Read the Contributing Guidelines
  • Read the README
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A open a GitHub Discussion.

Browser freeze with 7kb json lang file.

I try use localizations tab in new vue cli UI (/addon/org.kazupon.vue-i18n/)
After putting my project lang file in locales dir, i click localizations tab , my browser freeze for 20 sec before i see my keys and translations.

ua.zip

Empty .yml files throw a warnings

Reporting a bug?

When an empty .yml file gets loaded, the Loader throws a warning when using the webpack loader.

An empty .yml file looking like this:

---

The thrown warning is:

WARNING in ./app/javascript/src/apps/LearningResource/locales/de-DE.yml 1:15
Module parse failed: Unexpected token (1:15)
File was processed with these loaders:
 * ./node_modules/@intlify/vue-i18n-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
> export default 

Expected behavior

There is no warning thrown, but the file is loaded, compiled the yml file to an empty javascript object

Reproduction

  1. Add the vue-i18n-loader via webpack with:
var path = require("path");

module.exports = {
  test: /\.(json5?|ya?ml)$/, // target json, json5, yaml and yml files
  type: "javascript/auto",
  loader: "@intlify/vue-i18n-loader",
  include: [
    // Use `Rule.include` to specify the files of locale messages to be pre-compiled
    path.resolve(__dirname, "..", "..", [INSERT YOUR PATH]),
  ],
};
  1. Add an empty yaml file
  2. Run the loader

System Info

Webpack 4 with:

  System:
    OS: macOS 11.5.2
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 2.77 GB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 14.17.1 - ~/.nvm/versions/node/v14.17.1/bin/node
    Yarn: 1.22.5 - /usr/local/bin/yarn
    npm: 6.14.13 - ~/.nvm/versions/node/v14.17.1/bin/npm
  Browsers:
    Brave Browser: 93.1.29.76
    Edge: 93.0.961.38
    Firefox: 90.0.2
    Safari: 14.1.2
  npmPackages:
    @intlify/vue-i18n-loader: ^3.0.0 => 3.0.0 
    vue: ^3.2.6 => 3.2.6 
    vue-i18n: ^9.1.7 => 9.1.7

Screenshot

No response

Additional context

No response

Validations

  • Read the Contributing Guidelines
  • Read the README
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A open a GitHub Discussion.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency eslint-plugin-prettier to v5
  • chore(deps): update dependency jest-puppeteer to v10
  • chore(deps): update dependency jsdom to v24
  • chore(deps): update dependency lerna-changelog to v2
  • chore(deps): update dependency prettier to v3
  • chore(deps): update dependency puppeteer to v22
  • chore(deps): update dependency typescript to v5
  • chore(deps): update dependency typescript-eslint-language-service to v5
  • chore(deps): update dependency vue to v3
  • chore(deps): update dependency vue-i18n to v9
  • chore(deps): update dependency vue-loader to v17
  • chore(deps): update dependency webpack-cli to v5
  • chore(deps): update dependency webpack-dev-server to v5
  • chore(deps): update typescript-eslint monorepo to v7 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • fix(deps): update dependency js-yaml to v4 (js-yaml, @types/js-yaml)
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/release.yml
  • actions/checkout v1
  • actions/setup-node v1
.github/workflows/test.yml
  • actions/checkout v2
  • actions/setup-node v1
npm
package.json
  • @intlify/shared ^9.0.0
  • js-yaml ^3.13.1
  • json5 ^2.1.1
  • @types/jest ^26.0.16
  • @types/js-yaml ^3.12.1
  • @types/jsdom ^16.2.5
  • @types/json5 ^0.0.30
  • @types/memory-fs ^0.3.2
  • @types/node ^14.14.10
  • @types/webpack ^4.41.26
  • @types/webpack-merge ^4.1.5
  • @typescript-eslint/eslint-plugin ^4.15.0
  • @typescript-eslint/parser ^4.15.0
  • babel-loader ^8.1.0
  • eslint ^7.21.0
  • eslint-config-prettier ^8.1.0
  • eslint-plugin-prettier ^3.3.1
  • eslint-plugin-vue-libs ^4.0.0
  • jest ^26.6.3
  • jest-puppeteer ^4.4.0
  • jest-watch-typeahead ^0.6.0
  • jsdom ^16.4.0
  • lerna-changelog ^1.0.1
  • memory-fs ^0.5.0
  • opener ^1.5.2
  • prettier ^2.0.4
  • puppeteer ^2.1.1
  • shipjs ^0.26.0
  • ts-jest ^26.4.4
  • typescript ^4.1.3
  • typescript-eslint-language-service ^4.1.3
  • vue ^2.6.11
  • vue-i18n ^8.23.0
  • vue-loader ^15.9.6
  • vue-template-compiler ^2.6.11
  • webpack ^4.46.0
  • webpack-cli ^3.3.12
  • webpack-dev-server ^3.11.0
  • webpack-merge ^4.2.2
  • node >= 10

  • Check this box to trigger a request for Renovate to run again on this repository

Multiple translations format

It would be nice to support YAML and JSON format side by side. It can be achieved for example by adding attribute lang="yaml".

Also, with vue-loader v15 I cannot make YAML working inside i18n block by any means. Supporting YAML natively would solve my problem.

Single File Component doesn't work anymore

Reporting a bug?

I copied step by step the code in your README but it doesn't work.

the translation works fine if we use a message object, but as soon as we use the tag, it doesn't work, and I see the error in the console:

[vue-i18n] Value of key 'hello' is not a string or function !
[vue-i18n] Cannot translate the value of keypath 'hello'. Use the value of keypath as default.

I have tried to make this work, with webpack, vue-cli, etc. but it just doesn't work, at least not with just the steps in the documentation.

Expected behavior

Instead of hello which is the name of the key it should show the value of this key, so "hello world!" or "こんにちは、世界!"

Reproduction

https://codesandbox.io/s/brave-water-spm7l4

System Info

System:
    OS: Windows 10 10.0.22000
    CPU: (16) x64 12th Gen Intel(R) Core(TM) i5-12600K
    Memory: 3.92 GB / 15.78 GB
  Binaries:
    Node: 16.14.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 8.3.1 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.22000.120.0), Chromium (99.0.1150.46)
    Internet Explorer: 11.0.22000.120

Screenshot

image

Additional context

No response

Validations

Decoding\Unescaping quotes and other characters in regular text

Hello,
in text containing encoded or escaped quotes I cannot get it to show properly if I am not using v-html.
I'm using translations from a json file so if any text uses double or single quotes I will need to escape it in the file either by adding a slash or by encoding it.
But I am not always using v-html in the content of pages to ensure decoding, most of the time I'm just using the {{ }} syntax in Vue.

Is there a workaround for this?

Will i18n be included in buildfile when compiling?

Maybe im asking stupid question but upon compiling the app will the i18n tag (single file component) be included in the buildfile? My concern for it is that i have an app that supports multiple language so i have different builds for it (separate deployment thats why).

Element i18n doesn't have required attribute path

According to your examples here on GitHub I use this syntax in my Vue components

<i18n lang="yml" locale="en">
dismiss_all: Dismiss all
</i18n>

<i18n lang="yml" locale="de">
dismiss_all: Alle entfernen
</i18n>

Today I recognized that IntelliJ complains about missing required path attribute.

I use version 1.0.0 of @intlify/vue-i18n-loader.

Maybe there is a invalid dtd somewhere in the package?

SFC i18n block breaks debug

I'm currently using VSCode for vue frontend development, and when i add single block, to any component, IDE debug totally brokes for entire project. I cant find what causes wrong behavior, but i am pretty sure, that it happens when i add this block.

Doesn't work with "pluralizationRules"

const i18n = createI18n({
    locale: "ru", // set locale
    pluralizationRules: {
        ru: function () {debugger;}
    }
});
<template>
        <div>
            {{ $tc("комментарий", 3) }}
        </div>
</template>
<i18n>
{
    "ru": {
        "комментарий": "{count} комментариев | {count} комментарий | {count} комментария | {count} комментария"
    }
}
</i18n>

in this case debugger will NEVER called.

But, when I placed translation here:

const i18n = createI18n({
    locale: "ru", // set locale
    pluralizationRules: {
        ru: function () {debugger;}
    },
    messages: {
      "ru": {
          "комментарий": "{count} комментариев | {count} комментарий | {count} комментария | {count} комментария"
      }
  }
});

all works fine!

@intlify/vue-i18n-loader: 2.0.0-rc.1

npm command not working

Hello,

I tried to install vue-i18n-loader this morning with the standard command:
npm i --save @kazupon/vue-i18n-loader

I have the following error:

npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "i" "@kazupon/vue-i18n-loader" "--save"
npm ERR! node v6.10.1
npm ERR! npm  v3.10.10
npm ERR! code E404

npm ERR! 404 no such package available : @kazupon/vue-i18n-loader
npm ERR! 404
npm ERR! 404  '@kazupon/vue-i18n-loader' is not in the npm registry.

I also tried to add it manually in the package.json with the same effect:
"@kazupon/vue-i18n-loader": "^0.2.1"

I found a strange workaround removing the @ in the command line:
npm i --save kazupon/vue-i18n-loader
=> it adds the following ugly line in the dependencies:
"@kazupon/vue-i18n-loader": "github:kazupon/vue-i18n-loader"

It works but it's not clean.

question - load term from db

hi, fist thanks for great work.
Im just curious if there is a way to load i18 translations dynamicaly via fetch call from backend? any idea or example would be helpfull.

vue-i18n-loader do not use external vue in webpack config.

I want to use i18n in single file component, if I use external Vue, add the config block below to webpack.config.js

      externals: {
        "vue$": "Vue",
      },

then I get the error from vue.runtime.esm.js:574 ,

vue.runtime.esm.js:574 [Vue warn]: Property or method "$t" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <App> at src\component\forecast-report\forecast-report.vue
       <Root>

When using the custom block, translations in the Vuei18n constructor are gone

Like the title says, when a custom block of <i18n> is used in a SFC, the already set translations are gone, for example:

I construct VueI18n as follows:

new VueI18n({
  locale: 'nl',
  fallbackLocale: 'en',
  messages: {
    nl: {
      hello: 'Hallo!'
    }
  }
})

Inside the SFC:

<i18n locale="en">
{
  "hello": "Hello!"
}
</i18n>
<!-- or even: --!>
<i18n>
{
  "en": {
    "hello": "Hello!"
  }
}
</i18n>

When you log the following in the mounted hook:

console.log(this.$i18n.messages);

You will notice that only the translations defined inside the custom block are still there, the others, defined in the constructor are gone...

Why is this? Is it possible to have them merged?

Using vue-i18n-loader with karma

I have set my .vue loader properly, and it works properly on chrome, but when I run my karma unit test suite (which uses the same web-pack config with a few changes), I get the following message for all my translations:

[vue-i18n] Cannot translate the value of keypath 'example_key'. Use the value of keypath as default.

Is there something that needs to be done in order to have this plugin work with karma-webpack?

Scoping of i18n blocks in components

I have multiple components with one or more <i18n> blocks, and I noticed what I think is a scoping issue (or at least not clear from the documentation).

What I see:

  1. I load a component (ComponentA). All its translations in i18n blocks are added to the root i18n object. It has a "title" translation.
  2. I load a second component (ComponentB). All its translations in i18n blocks are added to the root i18n object. It also has a "title" translation. Existing translations are overwritten.
  3. ComponentA now displays the title from ComponentB.

What I expected:

  1. I load a component (ComponentA). All its translations in i18n blocks are added to a scoped section in the root i18n object. It has a "title" translation.
  2. I load a second component (ComponentB). All its translations in i18n blocks are added to a scoped section in the root i18n object. It also has a "title" translation, but it won't overwrite the "title" translation of ComponentA since both i18n blocks are scoped.
  3. ComponentA and ComponentB display their own titles.

Possible solutions (feature request):

  1. Scope i18n blocks in components by default (breaking change)
  2. Support <i18n scoped> (my preferred solution)

In any case, I feel the documentation could be more explicit on the current behavior.

A translation that has the '@' symbol in the JSON translation file an error will occur

Reporting a bug?

If there is a translation in a translation file (e.g. 'en.json') that contains the symbol @ the loader will return the error Module build failed: Error: Final loader (./node_modules/@intlify/vue-i18n-loader/lib/index.js) didn't return a Buffer or String. It seems like vue-i18n-loader does not realize it is text.

Expected behavior

I expect my translations to be displayed on the page, not to receive an error message.

Reproduction

I ran this using the runtime version of vue-i18n (vue-i18n/dist/vue-i18n.runtime.esm-bundler.js), @intlify/vue-i18n-loader and webpack.

System Info

I ran this using the runtime version of vue-i18n (vue-i18n/dist/vue-i18n.runtime.esm-bundler.js) and @intlify/vue-i18n-loader using webpack.

Screenshot

No response

Additional context

No response

Validations

  • Read the Contributing Guidelines
  • Read the README
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A open a GitHub Discussion.

How to use vue-i18n-loader with vue-loader 15?

With vue-loader 14, my Webpack 4 config has the following block:

{
  test: /\.vue$/,
  loader: 'vue-loader',
  options: {
    loaders: {
      i18n: '@kazupon/vue-i18n-loader'
    }
  }
},

After upgrading to the release candidate of vue-loader 15, none of my translations work, vue-i18n doesn't load any translation from <i18n> blocks within the .vue files.

Is this a known limitation or do I have to change anything in the Webpack 4 config? For vue-loader 15, I had to add new VueLoaderPlugin(), in the plugins section after adding const { VueLoaderPlugin } = require('vue-loader')

Lazy loading compatibility

Does the use of <i18n> blocks inside of components defeat the point of lazy loading? Or does webpack handle this some how even though the strings aren't stored in separate files before build?

Can't deal with "-" and "_" in locale json file

I try to make file "zh-cn.json", but loader failed to load that file(fallback used). I renamed file to "zh_cn.json", it still didn't work for same reason. If I used "zhcn.json", it worked.

It seems not to be able to use "_" and "-" in locale json file.

Not translate from tag <i18n>

Vue ver: 2.6.12
vue-i18n ver: 8.22.2
intlify/vue-i18n-loader ver: 1.0.0

I added to vue.config.js configuration:

chainWebpack: config => {
config.module
    .rule('i18n')
    .resourceQuery(/blockType=i18n/)
    .type('javascript/auto')
    .use('i18n')
    .loader('@intlify/vue-i18n-loader')
}

Next I added to main.js library vue-i18n:

import VueI18n from 'vue-i18n'
import { languages } from '@/locales'
Vue.use(VueI18n)

const i18n = new VueI18n({
    locale: 'en',
    fallbackLocale: 'en',
    silentTranslationWarn: true,
    messages: Object.assign(languages),
})

new Vue({
    el: '#app',
    i18n,
    components: {
        App,
    },
    template: '<App/>',
})

I have too languages object with translation word:

{
  "hi": "hi translate...",
}

Next I added to my component word to translate:

<template>
    <div>
        <div>{{ $t('hi') }}</div>
        <div>{{ $t('hello') }}</div>
    </div>    
</template>

<i18n>
{
  "en": {
      "hello": "hello translate..."
  },
}
</i18n>

When I trying translate word 'hi' everything work correctly, but when I try translate word 'hello' then nothing isn't translated

When I check language in component I get en:

created() {
    console.log(this.$i18n.locale) // en
},

Not working translate from tag <i18n>

Not working with `v-t` directive

Problem

The v-t directive only loads the global context. The following code does not work:

<i18n locale="en">
{
    "test": "Hello World"
}
</i18n>
<template>
    <p v-t="'test'"></p>
</template>

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

DateTime formating without hardcode

Hi guys,

Firstly I want to send many many thanks to the team for your awesome project.

Second, I want to know how to format date time without hardcode:

  • Currently, I use this code this.$d(new Date(), 'short', 'vi-VN') in Vue methods's scope
  • My locale variable is: this.$i18n.locale = 'vn'
  • I dont want hardcode 'vi-VN' value, so I try this.$d(new Date(), 'short', this.$i18n.locale), but it not worked.
    How could I make this code work so that I don't have to hardcode 'vi-VN' value?

Thank in advanced!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.