Vue config js где найти
Перейти к содержимому

Vue config js где найти

  • автор:

# Конфигурация сборки

Конфигурация webpack для проекта с SSR аналогична конфигурации проекта только для клиентской стороны. Если ещё не знакомы с настройкой webpack, более подробную информацию можно найти в документации Vue CLI

# Ключевые отличия от сборки только для клиента

  1. Необходимо создать манифест webpack
"scripts":  "build:client": "vue-cli-service build --dest dist/client", "build:server": "SSR=1 vue-cli-service build --dest dist/server", "build": "npm run build:client && npm run build:server", > 

# Пример конфигурации

Ниже приведён пример vue.config.js , который добавляет SSR в проект Vue CLI, но его можно адаптировать для любой сборки webpack.

const  WebpackManifestPlugin > = require('webpack-manifest-plugin') const nodeExternals = require('webpack-node-externals') const webpack = require('webpack') module.exports =  chainWebpack: webpackConfig =>  // Необходимо отключать cache-loader, иначе в сборке для клиента // будут использоваться кэшированные компоненты из сборки для сервера webpackConfig.module.rule('vue').uses.delete('cache-loader') webpackConfig.module.rule('js').uses.delete('cache-loader') webpackConfig.module.rule('ts').uses.delete('cache-loader') webpackConfig.module.rule('tsx').uses.delete('cache-loader') if (!process.env.SSR)  // Определяем точку входа клиентской части приложения webpackConfig .entry('app') .clear() .add('./src/entry-client.js') return > // Определяем точку входа серверной части приложения webpackConfig .entry('app') .clear() .add('./src/entry-server.js') // Это позволяет webpack обрабатывать динамические импорты в соответствии // с подходом в Node, а также указывает `vue-loader` выдавать // серверно-ориентированный код при компиляции компонентов Vue. webpackConfig.target('node') // Это указывает сборке для сервера использовать экспорты в стиле Node webpackConfig.output.libraryTarget('commonjs2') webpackConfig .plugin('manifest') .use(new WebpackManifestPlugin( fileName: 'ssr-manifest.json' >)) // https://webpack.js.org/configuration/externals/#function // https://github.com/liady/webpack-node-externals // Экстернализация зависимостей приложения. Это сделает сборку для сервера // гораздо быстрее и создаст более лёгкий файл итоговой сборки. // Не нужно экстернализировать зависимости, которые должны обрабатываться webpack. // Также следует внести в белый список зависимости, которые изменяют `global` (например, полифилы) webpackConfig.externals(nodeExternals( allowlist: /\.(css|vue)$/ >)) webpackConfig.optimization.splitChunks(false).minimize(false) webpackConfig.plugins.delete('preload') webpackConfig.plugins.delete('prefetch') webpackConfig.plugins.delete('progress') webpackConfig.plugins.delete('friendly-errors') webpackConfig.plugin('limit').use( new webpack.optimize.LimitChunkCountPlugin( maxChunks: 1 >) ) > > 

# Предостережения для externals

Обратите внимание, что в опции externals в белый список добавляются CSS-файлы. Это связано с тем, что CSS импортируемый из зависимостей, всё равно должен обрабатываться webpack. Если импортируете файлы других типов, которые также полагаются на webpack (например, *.vue , *.sass ), их тоже следует добавить в белый список.

При использовании runInNewContext: ‘once’ или runInNewContext: true необходимо добавить в белый список полифилы, изменяющие global (например, babel-polyfill ). Это требуется для того, что при использовании режима нового контекста код внутри сборки для сервера будет иметь свой собственный объект global . Поскольку на сервере он не нужен, проще просто импортировать его в файл клиентской точки входа.

# Генерация clientManifest

В дополнение к серверной сборке также можно сгенерировать манифест клиентской сборки. Благодаря клиентскому манифесту и серверной сборке, рендерер будет иметь информацию как о серверной так и о клиентской сборках. Благодаря этому он сможет автоматически определять и внедрять директивы для preload / prefetch

Выгода от этого двойная:

  1. Он заменяет html-webpack-plugin для внедрения корректных URL ресурсов, когда в именах генерируемых файлов присутствуют хэши.
  2. При генерации сборки, которая использует возможности webpack по разделению кода, можно обеспечить preload / prefetch необходимых фрагментов, а также интеллектуально внедрять теги для требуемых асинхронных фрагментов, чтобы избежать водопада запросов на клиенте, тем самым улучшая TTI (time-to-interactive).

(opens new window)
Последнее обновление страницы: около 2 лет назад

Ми­гра­ция с Vue CLI на Vite

Я недавно переносил свои проекты на Vue 2 со стэка Vue CLI и Webpack на Vite. После того, как я сделал это в третий раз, у меня сложилось представление об этом процессе, которое я излагаю в этой статье.

package.json Скопировать ссылку

devDependencies Скопировать ссылку

Давайте удалим зависимость @vue/cli-service и заменим её на vite ��

npm un @vue/cli-service npm i vite -D 
 "devDependencies": < - "@vue/cli-service": "4.3.1", + "vite": "2.1.3", 

Вы можете также удалить все остальные зависимости, которые начинаются с @vue/cli-plugin-xxx , поскольку они всё равно больше не будут работать, например:

npm un vue/cli-plugin-babel vue/cli-plugin-eslint vue/cli-plugin-unit-jest 
 "devDependencies": < - "@vue/cli-plugin-babel": "4.3.1", - "@vue/cli-plugin-eslint": "4.3.1", - "@vue/cli-plugin-unit-jest": "4.3.1", 

Если вы используете Vue 2, нужно будет добавить плагин vite-plugin-vue2 , который мы будем использовать в нашем vite.config.js :

npm i vite-plugin-vue2 -D 
 "devDependencies": < + "vite-plugin-vue2": "1.4.2", 

Также, если вы используете Git-хуки, без сомнения нужно будет установить yorkie , чтобы все заработало как раньше (думаю, что этот инструмент был частью Vue CLI, а в Vite его нет).

npm i yorkie -D 

scripts Скопировать ссылку

Мы заменим скрипт serve для Vue CLI на соответствующий скрипт для Vite:

 "scripts": < - "serve": "vue-cli-service serve", + "dev": "vite", 

Если вам ближе использование слова serve вместо dev , можете использовать и его.

Мы еще вернемся к скриптам build , test и lint в конце статьи.

index.html Скопировать ссылку

Давайте посмотрим на наш public/index.html , который мы должны переместить в корневую папку проекта.

Мы также должны добавить скрипт, который является точкой входа приложения и без которого Vite не сможет собрать проект:

И наконец, мы должны заменить путь до фавиконки favicon.ico на более простой /favicon.ico (Vite сможет отыскать его сам в папке public ).

    - favicon.ico"> + … +  

vite.config.js Скопировать ссылку

Мы должны переименовать наш файл с конфигурацией сборки с vue.config.js на vite.config.js .

В начале файла нужно указать следующее:

import < defineConfig >from 'vite' import < createVuePlugin >from 'vite-plugin-vue2' export default defineConfig(< plugins: [ createVuePlugin(), ], >) 

Чтобы сделать миграцию на Vite максимально прозрачной для вашей команды разработчиков, давайте оставим тот же порт 8080 , который и был:

import < defineConfig >from 'vite' import < createVuePlugin >from 'vite-plugin-vue2' export default defineConfig( < server: < port: 8080, >>) 

Все доступные опции для конфигурации можно посмотреть в документации.

@ alias Скопировать ссылку

Если вы используете псевдонимы Webpack для импортов в файлах вашего проекта, мы должны переопределить их:

import < defineConfig >from 'vite' import < createVuePlugin >from 'vite-plugin-vue2' export default defineConfig( < resolve: < alias: [ < find: '@', replacement: path.resolve(__dirname, 'src') >] >, >) 

Для пользователей WebStorm: при использовании Webpack вам достаточно было прописать в настройках IDE путь до файла с конфигурацией Webpack (для Vue CLI это был путь до базового файла Webpack: node_modules/@vue/cli-servive/webpack.config.js ) и WebStorm магическим образом подхватывал псевдоним @ , что позволяло очень просто обращаться к библиотекам.

Пока WebStorm не умеет парсить vite.config.js , и мы должны помочь ему, прописав настройки псевдонимов вручную в webStorm.config.js :

System.config(< paths: < '@/*': './src/*', >, >) 

Это всё, что вы должны сделать 🙂

Расширение .vue и импорты Скопировать ссылку

Для Webpack было совершенно не обязательно указывать расширение .vue для файлов компонентов, но не для Vite. Нужно заменить:

- import DotsLoader from '@/components/DotsLoader' + import DotsLoader from '@/components/DotsLoader.vue' 

Не по теме, но из моего опыта: использовать импорты с полными путями — лучшая практика.

Очистка маршрутов для ленивой загрузки Скопировать ссылку

Вы со спокойной душой можете удалить комментарии webpackChunkName для генерации чанков для определенных маршрутов:

 < path: '/links', name: 'linksPage', component: () =>import(/* webpackChunkName: "links" */ './views/LinksPage.vue'), >, 

Используя Vite можно писать так:

 < path: '/links', name: 'linksPage', component: () =>import('./views/LinksPage.vue'), >, 

Я в этом не эксперт, но если вы действительно хотите изменить имя для вашего чанка, вероятно, вы можете это сделать принудительно с помощью Rollup output.entryFileNames .

Также, можете посмотреть опции для сборщика Vite build.rollupOptions и перенести часть задач на него.

Переменные окружения Скопировать ссылку

Мы должны заменить все process.env , которые Vite не понимает. Для Vite нужно использовать import.meta.env .

Если ваш роутер использует встроенную переменную окружения BASE_URL , то ее имя надо будет заменить на import.meta.env.BASE_URL :

 const router = new Router(< mode: 'history', - base: process.env.BASE_URL, + base: import.meta.env.BASE_URL, routes: [. firstLevelRoutes, . backOfficeRoutes] >) 

Другой встроенной переменной окружения является import.meta.env.PROD . Давайте будем использовать её везде, где можем:

- if (process.env.NODE_ENV === 'production') < + if (import.meta.env.PROD)  

Убедитесь, что настройка NODE_ENV=production соответствует настройкам среды в файле .env или в переменных окружения сервера, на котором собирается ваше приложение во время релиза. Подробнее можно посмотреть в документации по переменным окружения и режимах работы Vite.

Что касается ваших собственных переменных окружения, которые вы использовали раньше с префиксом VUE_APP — вам нужно будет заменить его на VITE . Любая переменная окружения, которая будет начинаться с VITE_xxx , будет доступна во всём вашем коде.

Вот пример для моей переменной окружения BACKEND_URL :

 export const backendInstance = axios.create(< - baseURL: `$/api`, + baseURL: `$/api`, timeout: 10000, >) 
VITE_APP_BACKEND_URL=http://localhost:3001 

Тесты Скопировать ссылку

Поскольку мы больше не можем использовать vue-cli-service test:unit , давайте настроим наши тесты.

Для начала надо обновить скрипт для тестов test :

- "test:unit": "vue-cli-service test:init", + "test": "jest", 

Затем пройдемся по шагам, описанным в документации.

Если вы использовали файл babel.config.js , то нужно будет сделать что-то вроде:

- presets: ['@vue/cli-plugin-babel/preset'], + presets: ['@babel/preset-env'], 

У меня были ошибки для выражения import.meta.env .

К сожалению, простых настроек для модульных тестов в Vite нет, но этот комментарий мне помог.

Мой файл babel.config.js теперь выглядит так:

module.exports = < presets: ['@babel/preset-env'], // Чтобы Jest не нервировали 'import.meta.xxx' plugins: [ function () < return < visitor: < MetaProperty(path) < path.replaceWithSourceString('process') >, >, > >, ], > 

Вы можете усилить сборку плагином babel-plugin-transform-import-meta для Babel, который будет исправлять автоматически ошибки в ваших тестах, связанные с import.meta .

Вы можете почитать и обсудить в отдельном ишью на GitHub совместную работу Vite и Jest.

Ошибка regeneratorRuntime Скопировать ссылку

 49 | export const actions = < >50 | init: async (< commit >, routeContext) => < ReferenceError: **regeneratorRuntime** is not defined 

Устанавливая regenerator-runtime и ссылаясь на него в моем setupTests.js , я обнаружил, что эту ошибку уже починили.

npm i regenerator-runtime -D 
module.exports = < moduleFileExtensions: [ 'js', 'json', // Говорит Jest обрабатывать файлы *.vue 'vue', ], transform: < // Обработай файл *.vue с помощью vue-jest '.*\\.(vue)$': 'vue-jest', // Обработай файлы *.js с помощью babel-jest '.*\\.(js)$': 'babel-jest', >, setupFiles: ['./setupTests'], moduleNameMapper: < '^@/(.*)$': '/src/$1', >, collectCoverage: false, > 

Первая строчка файла конфигурации setupTests.js будет такой:

import 'regenerator-runtime/runtime' 

Линтер Скопировать ссылку

Я заменил два скрипта для линтинга одним:

- "lint": "vue-cli-service lint src --no-fix", - "lint:fix": "vue-cli-service lint src", + "lint": "eslint src", + "lint:fix": "eslint src --fix", 

Развертывание приложений Скопировать ссылку

В этом примере мое приложение крутится в облаке S3 и CloudFront. У меня два окружения для режима продакшена: preprod и prod . Поэтому у меня и два файла для настройки окружения .env :

Когда мы собираем наше приложение с помощью Rollup, мы указываем режим, и Vite меняет переменные окружения на те, которые соответствуют этому режиму.

Это очень похоже на Vue CLI, поэтому обновление скриптов в package.json очень простое:

- "build-preprod": "vue-cli-service build --mode preprod", - "build-prod": "vue-cli-service build --mode prod", + "build-preprod": "vite build --mode preprod", + "build-prod": "vite build --mode prod", 

Если вам нужно больше подробностей, они хорошо описаны в документации.

Небольшая ремарка: мне пришлось также поменять максимальный размер для чанка в vite.config.js :

import < defineConfig >from 'vite' import < createVuePlugin >from 'vite-plugin-vue2' export default defineConfig(< build: < // По умолчанию 500 chunkSizeWarningLimit: 700, >, >) 

Так делать нехорошо, я знаю.

Визуализация сборки Скопировать ссылку

Это последнее упоминание Vue CLI, которое было в моей кодовой базе:

"build:report": "vue-cli-service build --report", 

Давайте поищем что-то похожее в мире Rollup. Использование плагина rollup-plugin-visualizer оказалось достаточно хорошим решением для меня.

Я импортировал этот плагин и прописал его в vite.config.js :

import < defineConfig >from 'vite' import < createVuePlugin >from 'vite-plugin-vue2' import visualizer from 'rollup-plugin-visualizer' export default defineConfig(< plugins: [ createVuePlugin(), visualizer(), ], >) 

Результат теста в сгенерированном файле stats.html :

Обзор содержимого JS-бандла.

Несколько метрик Скопировать ссылку

Время старта Скопировать ссылку

  • Загрузка Vite: около 4 секунд — предполагается, что это время не сильно изменится, даже если проект будет расти ��
  • Загрузка с Vue CLI и Webpack: около 30 секунд — это время постоянно растет при увеличении количества файлов в проекте ��

Горячая перезагрузка Скопировать ссылку

Vite:

  • Простые изменения (HTML-файлы, CSS-классы): очень быстро! ��
  • Серьёзные изменения (переименование функций JS, добавление компонентов): не уверен, иногда мне было удобнее перезагрузить страницу самому.

Vue CLI и Webpack:

  • Простые изменения: около 4 секунд ��
  • Серьезные изменения: никогда не жду, сам перезагружаю страницу.

Первая загрузка страницы Скопировать ссылку

Мы запрашиваем страницу в первый раз после запуска Vite. У меня было веб-приложение с большим количеством компонентов. Давайте взглянем на вкладку Network в Chrome DevTools:

  • Vite: загрузка около 1430 JS-файлов длится примерно 11 секунд ��
  • Vue CLI и Webpack: загрузка около 23 JS-файлов длится примерно 6 секунд ��

Сравнение разных вариантов сборки в панели Network: слева Vite, справа Vue CLI.

Посмотрим, как будет развиваться проект. Пока у меня не было достаточного опыта использования Vite, но начало многообещающее. Надо будет ещё оценить все возможности этого сборщика. Например, заявлено, что в Vite круто реализована ленивая загрузка компонентов!

Заключение Скопировать ссылку

Поработав некоторое время с Vite, могу сказать, что это был очень приятный опыт �� И теперь все тяжелее и тяжелее работать с Webpack на других проектах!

Vue.js

Vue.js is a framework for developing user interfaces and advanced single-page applications. WebStorm provides support for the Vue.js building blocks of HTML, CSS, and JavaScript with Vue.js-aware code completion for components, including components defined in separate files, attributes, properties, methods, slot names, and more.

With the built-in debugger, you can debug your Vue.js code right in WebStorm, which can automatically generate the necessary run/debug configurations you need: an npm configuration that launches the development server and starts your application in the development mode and a JavaScript Debug configuration that launches a debugging session.

Before you start

  1. Make sure you have Node.js on your computer.
  2. Make sure a local Node.js interpreter is configured in your project: open the Settings dialog ( Control+Alt+S ) and go to Languages & Frameworks | Node.js . The Node interpreter field shows the default project Node.js interpreter. Learn more from Configuring a local Node.js interpreter.
  3. Make sure the Vue.js and JavaScript Debugger required plugins are enabled on the Settings | Plugins page, tab Installed . For more information, refer to Managing plugins.

Create a new Vue.js application

The recommended way to create a new Vue.js app is the create-vue official Vue project scaffolding tool, which WebStorm downloads and runs for you using npx.

You can still use Vue CLI, if you choose this option WebStorm also downloads and runs it with npx .

Of course, you can download any of these tools yourself or create an empty WebStorm project as described in Creating projects and bootstrap it with Vue.js and other tools, such as Vite, babel, webpack, ESLint, etc.

  1. Click Create New Project on the Welcome screen or select File | New | Project from the main menu. The New Project dialog opens.
  2. In the left-hand pane, choose Vue.js .
  3. In the right-hand pane:
    1. Specify The path to the folder where the project-related files will be stored.
    2. In the Node Interpreter field, specify the Node.js interpreter to use. Select a configured interpreter from the list or choose Add to configure a new one.
    3. From the Vue CLI list, select npx create-vue (recommended) or npx --package @vue/cli vue . Alternatively, for npm version 5.1 and earlier, install the package yourself by running npm install --g create-vue or npm install --g @vue/cli in your command-line shell or in the Terminal Alt+F12 . When creating an application, select the folder where the package is stored.
    4. To bootstrap your application with babel and ESLint, select the Use the default project setup checkbox.

    Create an empty WebStorm project

    1. Click Create New Project on the Welcome screen or select File | New | Project from the main menu. The New Project dialog opens.
    2. In the left-hand pane, choose Empty Project .
    3. Specify The path to the folder where the project-related files will be stored.
    4. When you click Create , WebStorm creates and opens an empty project.

    Install Vue.js in an empty project

    1. Open the empty project where you will use Vue.js .
    2. In the embedded Terminal ( Alt+F12 ) , type: npm install vue

    Start with an existing Vue.js application

    To continue developing an existing Vue.js application, open it in WebStorm and download the required dependencies.

    Open the application sources that are already on your machine

    • Click Open on the Welcome screen or select File | Open from the main menu. In the dialog that opens, select the folder where your sources are stored.

    Check out the application sources from your version control

    1. Click Get from VCS on the Welcome screen. Alternatively, select File | New | Project from Version Control or Git | Clone… from the main menu. Instead of Git in the main menu, you may see any other Version Control System that is associated with your project. For example, Mercurial or Perforce .
    2. In the dialog that opens, select your version control system from the list and specify the repository to check out the application sources from. For more information, refer to Check out a project (clone).

    Download the dependencies

    Opening an Angular application and downloading the dependencies from package.json

    1. Click Run 'npm install' or Run 'yarn install' in the popup: You can use npm, Yarn 1, or Yarn 2, refer to npm and Yarn for details.
    2. Select Run 'npm install' or Run 'yarn install' from the context menu of package.json in the editor or in the Project tool window.

    Project security

    When you open a project that was created outside WebStorm and was imported into it, WebStorm displays a dialog where you can decide how to handle this project with unfamiliar source code.

    Untrusted project warning

    Select one of the following options:

    • Preview in Safe Mode : in this case, WebStorm opens the project in a preview mode. It means that you can browse the project's sources but you cannot run tasks and script or run/debug your project. WebStorm displays a notification on top of the editor area, and you can click the Trust project… link and load your project at any time.
    • Trust Project : in this case, WebStorm opens and loads a project. That means the project is initialized, project's plugins are resolved, dependencies are added, and all WebStorm features are available.
    • Don't Open : in this case, WebStorm doesn't open the project.

    Projects created from the Welcome screen or via File | New | Project as described in Creating projects are automatically considered trusted.

    Write and edit your code

    In .vue files, WebStorm recognizes script , style , and template blocks. You can use JavaScript and TypeScript inside script tags, Style Sheet languages inside style tags, and HTML and Pug inside template tags.

    When you use TypeScript inside a script tag, WebStorm invokes the TypeScript Language Service for type checking and shows detected errors in the Errors and Compile errors tabs of the TypeScript tool window. For more information, refer to Verifying TypeScript. Alternatively, you can use TsLint as described in Linting TypeScript in Vue.js components using TSLint

    Vue.js components

    WebStorm recognizes the .vue file type and provides a dedicated .vue file template for Vue.js components.

    Create a Vue.js component

    Create a Vue.js component

    • In the Project tool window, select the parent folder for the new component, and then choose Vue Component from the list.

    You can also extract a new Vue.js component from an existing one without any copying and pasting but using a dedicated intention action or refactoring. All the data and methods used in the newly extracted template stay in the parent component. WebStorm passes them to the new component with properties and copies the related styles.

    Extract components

    1. Select the template fragment to extract and invoke component extraction:
      • To use the intention action, press Alt+Enter , and then choose Extract Vue Component from the list.
      • To use the refactoring, choose Refactor | Extract | Extract Vue Component from the main menu or from the context menu of the selection.
    2. Type the name of the new component. If this name is already used or invalid, WebStorm shows a warning. Otherwise, a new single-file component is created and imported into the parent component.

    The Extract Vue Component refactoring works only in-place, so make sure the In the editor refactoring option is selected on the Editor | Code Editing page of the IDE settings Control+Alt+S .

    Code completion

    Complete code inside script, style, and template blocks

    Vue.js: completion for ES6 inside <script></p><div class='code-block code-block-10' style='margin: 8px 0; clear: both;'>
<!-- 10agladky -->
<script src=

  • By default, WebStorm provides code completion for ECMAScript 6 inside script blocks and for CSS inside style blocks. tag" width="600" height="355" />
  • Inside the template tag, code completion Control+Space and navigation to the definition Control+B for Vue.js components and attributes is available.

Complete Vue.js properties and methods

  • WebStorm also suggests completion for Vue.js properties, properties in the data object, computed properties, and methods.

Complete slot names

  • WebStorm provides completion for the names of slots from library components and from components defined in your project. If your project contains a component with named slots, WebStorm shows suggestions for these names in the v-slot directive of a template tag. Completion for named Vue.js slots defined in your project
  • If you’re using Vuetify, Quasar, or BootstrapVue, code completion for slot names is also available. Completion for named Vue.js slots from library components

Complete components defined in separate files

  • If a component is defined in several files, WebStorm recognizes the links between the parts of the component and provides proper code completion for properties, data, and methods. For example, if the parts of your component are defined in separate JavaScript and stylesheet files that are linked in the vue file through the src attribute, properties defined in JavaScript are properly completed in the template as methods do. Completion for Vue.js components defined in separate files
  • Templates inside template literals in the template property of a component get completion just as if this code were inside a template tag. Completion for templates inside template literals within a template propertyCompletion is also available if a template is defined in a separate HTML file and then linked to the template property.

Complete code inside Vue.js injections

Within Vue.js injections inside HTML files, WebStorm recognizes Vue.js syntax and highlights your code accordingly. You can also get completion for symbols from Vue.js libraries that are linked from a CDN in an HTML file without adding these libraries to your project dependencies.

Download libraries linked via CDN

  1. Open the HTML file with a CDN link to an external Vue.js library. WebStorm highlights the link.
  2. To enable completion for the library, press Alt+Enter on the link and select Download library from the list. Alternatively, hover over the link and click Download library .

The library is added to the list of JavaScript libraries on the Settings | Languages and Frameworks | JavaScript | Libraries page. For more information, refer to Configuring a library added via a CDN link.

Parameter hints

Parameter hints show the names of parameters in methods and functions to make your code easier to read. By default, parameter hints are shown only for values that are literals or function expressions but not for named objects.

Configure parameter hints

  1. Open the Settings dialog ( Control+Alt+S ) and go to Editor | Inlay Hints .
  2. Expand Vue under Parameter names .
  3. Specify the context in which you want parameter hints shown by selecting the corresponding checkboxes. The preview shows how the changes you make in the settings affect the code appearance.
  4. For some methods and functions, WebStorm does not show parameter hints in any context. Click Exclude list. to view these methods and functions, possibly enable parameter hints for them, or add new items to the list.
  5. To hide parameter hints for any value type in any context, clear the Vue template checkbox under Parameter names .

Vue.js live templates

With WebStorm, you can use a collection of Live templates for Vue.js adapted from the collection created by Sarah Drasner.

  1. Type the abbreviation of the template to use or press Control+J and select it from the list of available templates.
  2. To expand the template, press Tab .
  3. To move from one variable to another inside the template, press Tab again.

Nuxt.js in Vue.js applications

With WebStorm, you can use the Nuxt.js framework in your Vue.js applications. The recommended way to set up a Nuxt.js app in WebStorm is use the create-nuxt-app command. Alternatively, you can install Nuxt.js in an existing project.

Create a project with create-nuxt-app
  1. Create an empty WebStorm project.
    1. Click Create New Project on the Welcome screen or select File | New | Project from the main menu. The New Project dialog opens.
    2. In the left-hand pane, choose Empty Project . In the right-hand pane, specify the application folder and click Create .
    Install Nuxt.js in an existing project
    • Open the embedded Terminal ( Alt+F12 ) and type: npm install --save nuxt
    Install the @nuxt/types package

    With the @nuxt/types package, you can get better code completion.

    Notification about missing @nuxt/types

    • If you’re using a Nuxt.js version from 2.9.0 onwards and don’t have the @nuxt/types package installed, WebStorm notifies you about it and suggests installing it as a development dependency. Click the Install @nuxt/types as dev dependency link in the notification popup. If you close the popup, you can still install @nuxt/types by clicking the Install @nuxt/types as dev dependency link in the Event Log tool window ( View | Tool windows | Event Log ).
    • Alternatively, open the embedded Terminal ( Alt+F12 ) and type: npm install --save-dev @nuxt/types
    Nuxt.js-aware coding assistance

    WebStorm suggests code completion and shows quick documentation for all core Nuxt.js components.

    Completion and quick doc for Nuxt component

    WebStorm resolves references to the Vuex store and provides highlighting and completion for them.

    Code completion for Vuex store

Code completion in nuxt.config.js

On hover, you’ll also see the Documentation popup showing the type information for the Nuxt options used in the file.

Quick documentation popup in nuxt.config.js

Module resolution

WebStorm supports Nuxt.js-specific webpack setup. Starting with Nuxt.js 2.12.0, WebStorm automatically finds the webpack.config.js configuration file and uses the module resolution rules from it for coding assistance.

Notification about using webpack.config.js for module resolution and code completion

TypeScript in Vue.js applications

If your Vue.js project is written in TypeScript, you need to choose the service to get coding assistance for .ts and .vue files from. That can be either WebStorm integration with the TypeScript Language Service, or the Vue Language server (Volar), or the internal WebStorm parser and code inspections.

For TypeScript 5.0.0 and later, the Vue Language Server (Volar) is used by default because the TypeScript Language Service is not supported for these versions.

For earlier versions, the default solution is integration with the TypeScript Language Service, but you can also use integration with the Vue Language Server (Volar).

The Vue Language Server (Volar) integration is used for error highlighting only. Code completion and navigation are provided by the WebStorm internal support.

  1. In the Settings dialog ( Control+Alt+S ), go to Languages & Frameworks | TypeScript | Vue .
  2. Specify the service to use.
    • By default, the Automatically option is chosen. In this mode, WebStorm detects the TypeScript version used in your project and enables integration with the appropriate service.
      • For TypeScript version 5.0.0 and later, WebStorm downloads the @vue/language-server package and uses the Vue Language Server (Volar).
      • For earlier versions of TypeScript, the TypeScript Language Service is used. Learn more from Configure integration with the TypeScript Language Service.
    • If you select Vue Language Server (Volar) , WebStorm will always provide coding assistance in .ts and .vue files through integration with the Vue Language Server, no matter which version of TypeScript you are using. Note that the Vue Language Server coding assistance will be restricted to error highlighting only. Code completion and navigation will be provided by the WebStorm internal support.
    • Select TypeScript to always use the TypeScript Language Service in .ts and .vue files. Note that the TypeScript Language Service does not work with TypeScript version 5.0.0 and later. Therefore, if your project is using one of these versions, error highlighting will be provided through the WebStorm internal code inspections.
    • Select Disabled to turn both the TypeScript Language Service and the Vue Language Server off and get coding assistance from the WebStorm internal support.
  3. In the Vue Language Server field, specify the Vue Language Server version to use. Accept the suggested default version or click Select and specify the path to a custom @vue/language-server package.

Formatting in Vue.js applications

Configure indentation

By default, code within top-level tags is indented uniformly, in the Vue.js-specific style. You can configure this indentation to depend on the language used, for example, be HTML or Pug-specific.

  1. In the Settings dialog ( Control+Alt+S ), go to Editor | Code Style | Vue Template , and open the Tabs and Indents tab.
  2. By default, the contents of all top-level tags are indented uniformly, in the Vue.js-specific style. Accept the default indentation settings or customize them using the controls on the page. As you change the settings, the Preview in the right pane shows how the changes affect code formatting. To have the code inside top-level tags indented with regard to its language, select Specific to the language in the block .
  3. In the Indent children of top-level tag field, specify the top-level tags where the code should have initial indentation. By default, only the code inside template tags has initial indentation. If necessary, add other tags using commas as separators. For example, if you specify script in the field, the code inside all script tags gets initial indentation as shown in the Preview pane.

Configure spaces

  1. By default, WebStorm automatically inserts spaces after the opening curly brace ( < ) and before the closing one ( >) in Vue.js text interpolations with Mustache syntax. To suppress inserting spaces automatically, open the Settings dialog ( Control+Alt+S ), go to Editor | Code Style | Vue Template , then open the Spaces tab and clear the Interpolations checkbox.
  2. By default, when you enclose a code fragment in a block comment, the text starts right after the opening /* characters without any spaces. Before the closing */ characters no space is inserted either. This default code style may conflict with some linters' rules, for example, ESLint. To improve the code style, configure enclosing block comments in leading and trailing spaces. In the Settings dialog ( Control+Alt+S ), go to Editor | Code Style | JavaScript or Editor | Code Style | TypeScript , open the Code Generation tab, and configure the spaces and formatting in the Comments area.

Configure wrapping and braces

  1. In the Settings dialog ( Control+Alt+S ), go to Editor | Code Style | Vue Template , and open the Wrapping and Braces tab.
  2. If a JavaScript expression inside a Vue.js interpolation has line breaks, WebStorm automatically starts this JavaScript expression from a new line and adds a new line after it. Clear the New line after '>' checkboxes to change this default behavior. These checkboxes do not affect JavaScript expressions without line breaks inside. For example, > will not be split automatically anyway.
  3. Configure multiple right margins as described in Vue.js code style: Visual guides.
  4. Configure wrapping in interpolations as described in Wrapping options.

Reformat Vue.js code with Prettier

You can configure Prettier to reformat specific files every time such file is changed and the changes are saved automatically or manually, refer to Run Prettier automatically on save.

Also, Prettier can be set as default formatter for specific files. It will run against such files every time you reformat your code with Control+Alt+L .

For more information, refer to Reformat code with Prettier.

Reformat code with Prettier

  • In the editor, select the code fragment to reformat. To reformat a file or a folder, select it in the Project tool window. Then press Command Alt Shift P or select Reformat with Prettier from the context menu.
  • To run Prettier automatically against specific files, open the Settings dialog ( Control+Alt+S ), go to Languages & Frameworks | JavaScript | Prettier , and use the On code reformatting and On save checkboxes to specify the actions that will trigger Prettier. For more information, refer to Run Prettier automatically on save and Set Prettier as default formatter.

WebStorm can apply the key code style rules from the Prettier's configuration to the WebStorm Code Style settings so that generated code (for example, after refactoring or quick-fix) and the code that is already processed with Prettier are formatted consistently.

Apply Prettier code style rules

Pane above package.json: apply Prettier code style

  • In the project where Prettier is enabled, open package.json and click Yes in the pane at the top of the tab.
  • To re-apply the Prettier code style (after you've clicked No in the pane or modified the code style), press Control+Shift+A and select Apply Prettier Code Style Rules from the Find Action list.

Linting TypeScript in Vue.js components using TSLint

You can lint TypeScript code in your Vue.js single file components using typescript-tslint-plugin.

Because typescript-tslint-plugin works only with TypeScript that is installed in the current project, make sure the typescript package from your project node_modules folder is selected in the TypeScript field on the TypeScript page of the Settings dialog ( Control+Alt+S ).

Install and configure typescript-tslint-plugin

  1. In the embedded Terminal ( Alt+F12 ) , type: npm install --save-dev typescript-tslint-plugin
  2. In the plugins property of your tsconfig.json file, type:

Running and debugging a Vue.js application

For applications created with create-vue in the WebStorm New Project wizard as described above, WebStorm generates two run/debug configurations with default settings:

  • An npm configuration with the default name npm dev . This configuration runs the npm dev command that launches the development server and starts your application in the development mode.
  • A JavaScript Debug configuration with the default name Debug Application . This configuration launches a debugging session.

If your application was created without using create-vue, you need to create an npm and a JavaScript Debug run/debug configurations with the actual settings, such as, host, port, etc., manually.

Run a Vue.js application

Vue.js app is running

  1. Select the npm dev run configuration from the list on the toolbar and click next to the list. Alternatively, run npm run dev in the Terminal Alt+F12 or double-click the dev task in the npm tool window ( View | Tool Windows | npm ).
  2. Wait till the application is compiled and the development server is ready. The Run tool window or the Terminal shows the URL at which your application is running, by default it is http://localhost:8080/ . Click this link to view the application.

When the development server is running, your application is automatically reloaded as soon as you change any of the source files and save the updates.

Debug a Vue.js application

You can start a debugging session in different ways depending on how your application was created and where it is running.

  • If your application was created with create-vue, start a debugging session through an autogenerated Debug Application configuration. See Debug applications created with create-vue below.
  • If your application is running on localhost , you can also start the debugger from the built-in Terminal or from the Run tool window. See Debug applications running on localhost below.
  • For debugging applications running on custom URLs, create a configuration of the type JavaScript Debug and specify the URL address at which your application is actually running. See Debug applications running on custom URLs below. This general workflow also works for applications running on localhost and for applications created with create-vue.

Debug applications created with create-vue

  1. Set the breakpoints in your code.
  2. Start the application in the development mode as described above and wait till the application is compiled and the development server is ready.
  3. Select the autogenerated Debug Application configuration from the list and click next to the list.

Debug applications running on localhost

  1. Set the breakpoints in your code.
  2. Start the application in the development mode as described above or by running and wait till the application is compiled and the development server is ready.
  3. The Run tool window or the Terminal shows the URL at which your application is running, by default it is http://localhost:8080/ . Hold Control+Shift and click this URL link. WebStorm starts a debugging session with an automatically generated Debug Application configuration of the type JavaScript Debug.

Debug applications running on custom URLs

the Debug button

  1. Set the breakpoints in your code.
  2. Start the application in the development mode as described above and wait till the application is compiled and the development server is ready.
  3. The Run tool window or the Terminal shows the URL at which your application is running. Copy this URL address, you will later specify it in a debug configuration. To view your application, just click the link.
  4. Create a JavaScript Debug configuration. To do that, go to Run | Edit Configurations on the main menu, click , and select JavaScript Debug from the list. In the Run/Debug Configuration: JavaScript Debug dialog, paste the saved URL in the URL field and save the configuration.
  5. To launch your newly created configuration, select it from the list of configurations and click next to the list.

When the first breakpoint is hit, switch to the Debug tool window and proceed as usual: step through the program, stop and resume program execution, examine it when suspended, explore the call stack and variables, set watches, evaluate variables, view actual HTML DOM, and so on.

Публикация #

Если вы используете Vue CLI с бэкенд-фреймворком, который обрабатывает статические ресурсы, как часть своей публикации, всё что вам нужно сделать, это убедиться, что Vue CLI генерирует файлы сборки в правильном месте, а затем следуйте инструкциям по публикации вашего бэкенд-фреймворка.

Если вы разрабатываете фронтенд вашего приложения отдельно от бэкенда — т.е. ваш бэкенд предоставляет только API с которым вы работаете, то по сути ваш фронтенд является чисто статическим приложением. Вы можете публиковать собранный контент в каталоге dist на любой статический файловый сервер, главное не забудьте установить правильный publicPath.

Локальный предпросмотр #

Каталог dist предназначен для обслуживания HTTP-сервером (если не задали publicPath относительным значением), поэтому не сработает если напрямую открыть dist/index.html через file:// протокол. Самый простой способ предпросмотра вашей сборки для production локально — использовать статический файловый сервер Node.js, например serve:

npm install -g serve # флаг -s означает запуск serve в режиме одностраничного приложения (SPA) # который решает проблему маршрутизации, описанную ниже serve -s dist 

Маршрутизация через history.pushState #

Если вы используете Vue Router в режиме history , простой статический файловый сервер не подойдёт. Например, если вы использовали Vue Router для маршрута /todos/42 , то сервер разработки уже был настроен для корректного ответа на запрос localhost:3000/todos/42 , но простой статический сервер используемый с production-сборкой будет отвечать ошибкой 404.

Чтобы это исправить, необходимо настроить production сервер так, чтобы index.html возвращался для любых запросов, не соответствующих статическим файлам. В документации Vue Router есть примеры конфигурации различных серверов.

CORS #

Если ваш статический фронтенд публикуется на домен, отличный от домена API бэкенда, то вам необходимо правильно сконфигурировать CORS.

PWA #

Если вы используете плагин PWA, ваше приложение необходимо публиковать по HTTPS адресу, чтобы Service Worker смог корректно зарегистрироваться.

Руководства для платформ #

GitHub Pages #

Публикация обновлений вручную #
  1. Установите корректное значение publicPath в vue.config.js . Если публикуете по адресу https://.github.io/ или на пользовательский домен, то можно опустить publicPath , так как оно по умолчанию "/" . Если вы публикуете по адресу https://.github.io// , (т.е. ваш репозиторий находится по адресу https://github.com// ), установите publicPath в значение "//" . Например, если ваш репозиторий называется "my-project", то ваш vue.config.js будет выглядеть примерно так:
// файл vue.config.js должен быть расположен в корневом каталоге проекта module.exports =  publicPath: process.env.NODE_ENV === 'production' ? '/my-project/' : '/' > 
#!/usr/bin/env sh # остановить публикацию при ошибках set -e # сборка npm run build # переход в каталог сборки cd dist # если вы публикуете на пользовательский домен # echo 'www.example.com' > CNAME git init git add -A git commit -m 'deploy' # если вы публикуете по адресу https://.github.io # git push -f git@github.com:/.github.io.git master # если вы публикуете по адресу https://.github.io/ # git push -f git@github.com:/.git master:gh-pages cd - 
Использование Travis CI для автоматических обновлений #
  1. Установите правильный publicPath в vue.config.js , как описано выше.
  2. Установите клиент Travis CLI: gem install travis && travis --login
  3. Сгенерируйте токен доступа на GitHub с правами доступа к репозиторию.
  4. Разрешите доступ Travis к репозиторию: travis env set GITHUB_TOKEN xxx ( xxx — это персональный токен доступа из шага 3.)
  5. Создайте файл .travis.yml в корневом каталоге проекта.
 language: node_js node_js: - "node" cache: npm script: npm run build deploy: provider: pages skip_cleanup: true github_token: $GITHUB_TOKEN local_dir: dist on: branch: master 

GitLab Pages #

Как описано в документации GitLab Pages, всё происходит с файлом .gitlab-ci.yml , расположенным в корневом каталоге проекта. Вы можете начать с этого рабочего примера:

# .gitlab-ci.yml файл расположен в корневом каталоге репозитория pages: # задание должно быть именованными страницами image: node:latest stage: deploy script: - npm ci - npm run build - mv public public-vue # GitLab Pages хук для каталога public - mv dist public # переименование каталога dist (результат команды npm run build) # опционально, можно активировать поддержку gzip с помощью следующей строки: - find public -type f -regex '.*\.\(htm\|html\|txt\|text\|js\|css\)$' -exec gzip -f -k > \; artifacts: paths: - public # путь к артефакту должен быть /public для GitLab Pages only: - master 

Как правило, по адресу https://yourUserName.gitlab.io/yourProjectName будет располагаться статический веб-сайт, поэтому потребуется создать файл vue.config.js для указания значения BASE_URL , соответствующего имени проекта (переменная окружения CI_PROJECT_NAME содержит его):

// файл vue.config.js расположен в корне вашего репозитория module.exports =  publicPath: process.env.NODE_ENV === 'production' ? '/' + process.env.CI_PROJECT_NAME + '/' : '/' > 

Изучите документацию по настройке домена в GitLab Pages для получения дополнительной информации об URL-адресе, где ваш веб-сайт будет размещён. Имейте ввиду, что можно также использовать собственный домен.

Закоммитьте оба файла .gitlab-ci.yml и vue.config.js перед push в ваш репозиторий. Будет запущен GitLab CI pipeline: при успешном выполнении, откройте Settings > Pages в вашем проекте, чтобы увидеть ссылку на свой сайт и нажмите на неё.

Netlify #

  1. На сайте Netlify добавьте новый проект из GitHub со следующими настройками:
  • Build Command: npm run build или yarn build
  • Publish directory: dist
  1. Нажмите кнопку публикации!
Использование режима history во Vue Router #

Для получения прямых хитов при использовании режима history во Vue Router, необходимо перенаправлять весь трафик в файл /index.html .

Рекомендуемый метод #

Создать файл netlify.toml в корневом каталоге репозитория со следующим содержимым:

[[redirects]] from = "/*" to = "/index.html" status = 200 
Альтернативный метод #

Создать файл _redirects в каталоге /public со следующим содержимым:

# Настройки Netlify для одностраничных приложений (SPA) /* /index.html 200 

При использовании @vue/cli-plugin-pwa убедитесь, что файл _redirects не кэшируется service worker.

Для этого добавьте в vue.config.js следующее:

// файл vue.config.js должен быть расположен в корневом каталоге проекта module.exports =  pwa:  workboxOptions:  exclude: [/_redirects/] > > > 

Render #

Render предлагает бесплатный хостинг статических сайтов с полностью управляемым SSL, глобальным CDN и непрерывным автоматическим развёртыванием из GitHub.

  1. Создайте новый Static Site в Render, и предоставьте доступ для GitHub-приложения Render в репозиторий.
  2. При создании используйте следующие значения:
  • Команда сборки: npm run build или yarn build
  • Каталог публикации: dist

Всё! Приложение будет доступно по URL-адресу Render сразу, как только завершится сборка.

Для того, чтобы получать прямые хиты при использовании режима history во Vue Router, необходимо добавить следующее правило на вкладке Redirects/Rewrites вашего сайта.

Amazon S3 #

Firebase #

Создайте новый проект Firebase в консоли Firebase. Рекомендуем изучить документацию о том, как настроить проект.

Убедитесь, что у вас глобально установлены firebase-tools:

npm install -g firebase-tools 

Из корня вашего проекта инициализируйте firebase с помощью команды:

firebase init 

Firebase задаст несколько вопросов о том, как настроить проект.

  • Выберите функции Firebase CLI, которые хотите настроить для проекта. Убедитесь, что выбрали hosting .
  • Выберите проект Firebase по умолчанию для вашего проекта.
  • Установите каталог public в значение dist (или куда генерируется итоговая сборка), который будет загружаться на Firebase Hosting.
// firebase.json  "hosting":  "public": "dist" > > 
  • Выберите yes чтобы настроить проект как одностраничное приложение. Это создаст index.html и в вашем каталоге dist и добавит настройки в hosting .
// firebase.json  "hosting":  "rewrites": [  "source": "**", "destination": "/index.html" > ] > > 

Запустите npm run build для сборки вашего проекта.

Для публикации вашего проекта на Firebase Hosting выполните команду:

firebase deploy --only hosting 

Если вы хотите использовать другие возможности Firebase CLI, которые вы используете в своём проекте для публикации, запустите firebase deploy без опции --only .

Теперь можно открыть проект по адресу https://.firebaseapp.com или https://.web.app .

Обратитесь к документации Firebase для получения более подробной информации.

Vercel #

Vercel — облачная платформа, позволяющая разработчикам хостить Jamstack веб-сайты и веб-сервисы, которые публикуются мгновенно, автоматически масштабируются и не требуют никакого контроля, всё это с zero-конфигурацией. Они обеспечивают глобальный доступ, SSL-шифрование, сжатие ресурсов, инвалидацию кэша и многое другое.

Шаг 1: Публикация проекта Vue на Vercel #

Для публикации проекта Vue с помощью Vercel для интеграции с Git, убедитесь, что он был выложен в Git-репозиторий.

Импортируйте проект в Vercel с помощью Import Flow. Во время импорта будут запрошены все соответствующие опции, предварительно сконфигурированные, но с возможностью изменения при необходимости.

После импорта проекта, все последующие push в ветку будут генерировать публикации для предпросмотра, а все изменения внесённые в ветку Production (обычно "master" или "main") будут приводить к публикации Production.

После публикации вы получите URL-адрес для просмотра приложения вживую, например: https://vue-example-tawny.vercel.app/.

Шаг 2 (опционально): Использование пользовательского домена #

При необходимости использовать пользовательский домен при публикации Vercel, можно Добавить или Перенаправить домен через настройки домена аккаунта Vercel.

Для добавления домена в проект, перейдите в раздел Проект на панели Vercel. После выбора проекта перейдите на вкладку "Настройки", затем выберите пункт меню Домены. На странице Домен вашего проекта, укажите домен которые хотите использовать в проекте.

После добавления домена, будут предоставлены различные методы его настройки.

Публикация свежего проекта на Vue #

Для публикации свежего проекта на Vue с настроенным Git-репозиторием, можно с помощью кнопки Deploy ниже:

Ресурсы: #

  • Пример исходного кода
  • Официальное руководство Vercel
  • Руководство по публикации Vercel
  • Документация по пользовательским доменам Vercel

Stdlib #

Heroku #

  1. Установите Heroku CLI
  2. Создайте файл static.json :
 "root": "dist", "clean_urls": true, "routes":  "/**": "index.html" > > 
git add static.json git commit -m "add static configuration" 
heroku login heroku create heroku buildpacks:add heroku/nodejs heroku buildpacks:add https://github.com/heroku/heroku-buildpack-static git push heroku master 

Surge #

Публикация с помощью Surge очень проста.

Сначала, вам потребуется собрать проект командой npm run build . И, если вы не установили утилиту Surge для командной строки, то вы можете сделать это командой:

npm install --global surge 

Затем перейдите в каталог dist/ вашего проекта, запустите surge и следуйте подсказкам на экране. Вас попросят указать электронную почту и пароль, если вы впервые используете Surge. Подтвердите каталог проекта, введите нужный домен и посмотрите как публикуется ваш проект, как примерно выглядит ниже.

 project: /Users/user/Documents/myawesomeproject/dist/ domain: myawesomeproject.surge.sh upload: [====================] 100% eta: 0.0s (31 files, 494256 bytes) CDN: [====================] 100% IP: **.**.***.*** Success! - Published to myawesomeproject.surge.sh 

Убедитесь, что ваш проект успешно опубликован с помощью Surge открыв в браузере myawesomeproject.surge.sh ! Дополнительные сведения о настройке, такие как конфигурация пользовательских доменов, можно найти на странице справки Surge.

Bitbucket Cloud #

  1. Как описывается в документации Bitbucket вам необходимо создать репозиторий названный в точности .bitbucket.io .
  2. Возможно публиковать в подкаталог, например, если требуется иметь несколько веб-сайтов. В этом случае укажите корректный publicPath в файле vue.config.js . Если публикуете по адресу https://.bitbucket.io/ , установку publicPath можно опустить, поскольку значение по умолчанию "/" . Если публикуете по адресу https://.bitbucket.io// , нужно задать publicPath в значение "//" . В этом случае структура каталогов должна отражать структуру URL-адресов, например, репозиторий должен иметь каталог / .
  3. В проекте создайте deploy.sh с указанным содержимым и запустите его для публикации:
#!/usr/bin/env sh # остановиться при ошибках set -e # сборка npm run build # переход в каталог итоговой сборки cd dist git init git add -A git commit -m 'deploy' git push -f git@bitbucket.org:USERNAME>/USERNAME>.bitbucket.io.git master cd - 

Docker (Nginx) #

Опубликуйте ваше приложение, используя nginx внутри docker контейнера.

  1. Установите docker
  2. Создайте файл Dockerfile в корневом каталоге проекта

FROM node:latest as build-stage WORKDIR /app COPY package*.json ./ RUN npm install COPY ./ . RUN npm run build FROM nginx as production-stage RUN mkdir /app COPY --from=build-stage /app/dist /app COPY nginx.conf /etc/nginx/nginx.conf 
**/node_modules **/dist 
user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events  worker_connections 1024; > http  include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; server  listen 80; server_name localhost; location /  root /app; index index.html; try_files $uri $uri/ /index.html; > error_page 500 502 503 504 /50x.html; location = /50x.html  root /usr/share/nginx/html; > > > 
docker build . -t my-app # Sending build context to Docker daemon 884.7kB # . # Successfully built 4b00e5ee82ae # Successfully tagged my-app:latest 
docker run -d -p 8080:80 my-app curl localhost:8080 # .  

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *