Why is lodash not working when I import it in Vue.js - vue.js

I created a fresh new install of vue.js using "vue create todo --default" command. After that I installed lodash too with this command "npm i --save lodash". I can see it in my package.json on the "dependencies" object. The problem is that when I import it on my main.js and use the lodash functions, it is showing the error "_ is not defined". So I tried importing it inside the App.vue. The error "_ is not defined" was removed but it is not working.
Here are the code inside the App.vue, main.js, and package.json
main.js
import Vue from 'vue'
import App from './App.vue'
import "bootstrap/dist/css/bootstrap.min.css";
import "jquery/dist/jquery";
import "bootstrap/dist/js/bootstrap.min";
import _ from "lodash";
Vue.prototype._ = _;
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<div id="app">
<h4 class="bg-primary text-white text-center p-2">
{{name}}'s' To Do List
</h4>
<div class="container-fluid p-4">
<div class="row">
<div class="col font-weight-bold">Task</div>
<div class="col-2 font-weight-bold">Done</div>
</div>
<div class="row" v-for="t in completedtask" v-bind:key="t.action">
<div class="col">{{t.action}}</div>
<div class="col-2">
<input type="checkbox" v-model="t.done" class="form-check-input">
{{t.done}}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
name: "Welly",
tasks: [{
action: "Buy Flowers",
done: false
},
{
action: "Get Shoes",
done: false
},
{
action: "Collect Tickets",
done: true
},
{
action: "Call Joe",
done: false
}
]
};
},
computed: {
hidecompletedtask(){
return _.map(this.tasks,(val)=>{
return !val.done;
});
}
}
}
</script>
<style>
</style>
package.json
{
"name": "todo",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"bootstrap": "^4.4.1",
"core-js": "^3.4.4",
"jquery": "^3.4.1",
"lodash": "^4.17.15",
"popper.js": "^1.16.1",
"vue": "^2.6.10"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^4.1.0",
"#vue/cli-plugin-eslint": "^4.1.0",
"#vue/cli-service": "^4.1.0",
"babel-eslint": "^10.0.3",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.0.0",
"vue-template-compiler": "^2.6.10"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"browserslist": [
"> 1%",
"last 2 versions"
]
}

You'll still need to access the prototype via the this context, like this._.map().
computed: {
hidecompletedtask() {
return this._.map(this.tasks, (val) => {
return !val.done;
});
}
}
Reference: Adding Instance Properties.
Alternatively, you could extend the global window object. Put the following line in your main.js (or some booting file).
window._ = require('lodash');
Somewhere else where you need the library:
computed: {
hidecompletedtask() {
// The underscore (_) character now refers to the `window._ object`
// so you can drop the `this`.
return _.map(this.tasks, (val) => {
return !val.done;
});
}
}

You can also use vue-lodash package -- Follow these steps:
npm install --save vue-lodash
in main.js -- import VueLodash from 'vue-lodash'
in main.js after import -- Vue.use(VueLodash)
Usage:
Vue._.random(20);
this._.random(20);
-------- OR ------------
In your main.js add this line of code:
window._ = require('lodash');
That way it will work without Vue or this:
Just do -- _.map()

You can import lodash in your main.js file by javascript window object like this:
window._ = require('lodash');
Then use it anywhere in your projet like this:
var original = [
{ label: 'private', value: 'private#johndoe.com' },
{ label: 'work', value: 'work#johndoe.com' }
];
var update = [
{ label: 'private', value: 'me#johndoe.com' },
{ label: 'school', value: 'schol#johndoe.com' }
];
var result = _.unionBy(update, original);
var sortedresult = _map(_.sortBy(result, 'label'));
console.log(sortedresult);
I just use lodash unionBy and sortBy method for example.

Related

[Vue warn]: Failed to resolve component: router-view

I'm a newbie to Vue.js and first time dealing with vue-router.
Just created a few files and for some reason I don't get to see the template. Compiled successfully but in the browser I get the following error: Failed to resolve component: router-view
main.js
import { createApp } from 'vue';
import VueRouter from 'vue-router';
import { store } from './store';
import App from './App.vue';
import AuthHandler from './components/AuthHandler';
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/oauth2/callback', component: AuthHandler }
]
});
const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')
App.vue
<template>
<div>
<AppHeader></AppHeader>
<router-view></router-view>
</div>
</template>
<script>
import AppHeader from "./components/AppHeader";
export default {
name: "App",
components: {
AppHeader
}
};
</script>
components/AuthHandler.vue
<template>
<div>
... Please wait
</div>
</template>
<script>
export default {
name: "AuthHandler"
};
</script>
Here is the package.json
package.json
{
"name": "images",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"lodash": "^4.17.21",
"qs": "^6.10.1",
"vue": "^3.0.0",
"vue-router": "^3.5.2",
"vuex": "^4.0.2"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
I resolved the problem in the following way. I believe the issue relay on the vue/vue-router versions. I hope this is the correct way :-)
main.js
import { createApp } from 'vue';
import App from './App.vue';
// import VueRouter from './vue-router';
import { createWebHistory, createRouter } from "vue-router";
import { store } from './store';
import AuthHandler from './components/AuthHandler';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/about', component: AuthHandler }
]
});
const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')
I was an idiot, I wanted to use 'vue add vue-router'. Of course it didn't work.
Vue add router
is the command.
npm install vue-router#4
only installs the package, won't add it to the app. If all is well, main.js should look like this:
import App from "./App.vue";
import router from "./router";
createApp(App).use(router).mount("#app");
Unfortunately they forgot to add it to the documentation...

Why does vue.js not work inside html files?

I wanted to add Vue.js to my Spring Boot application. Even though everything seem to build fine, I cannot make vue component work.
Here is my simple component, MenuBar.vue:
<template>
<div>
Menu
</div>
</template>
<script>
export default {
name: "MenuBar"
}
</script>
And here is HTML which should be using it:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<div id="vueApp">
<menu-bar></menu-bar>
</div>
<form th:action="#{/logout}" method="post">
<div><input type="submit" value="Log out"/></div>
</form>
</body>
</html>
Configuration files index.js:
import Vue from "vue";
import App from './App.vue'
Vue.config.devtools = true;
new Vue({
el: '#app',
template: '<App/>',
components: {App}
});
new Vue({
el: '#vueApp'
})
components.js:
import Vue from 'vue';
import MenuBar from "./components/MenuBar";
Vue.component('menu-bar', MenuBar);
And webpack config file:
// webpack.config.js
const {VueLoaderPlugin} = require('vue-loader');
const path = require('path');
module.exports = {
mode: 'development',
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
}
]
},
entry: {
main: path.resolve(__dirname, './src/index.js')
},
resolve: {
extensions: ['.vue', '.js'],
alias: {
'components': path.resolve(__dirname, './src/components/')
}
},
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin()
],
devServer: {
hot: false,
liveReload: true,
proxy: {
"*": {
target: 'http://localhost:8080',
ignorePath: false,
changeOrigin: false,
secure: false
}
},
port: 8081,
host: "0.0.0.0"
},
output: {
publicPath: '/dist/',
path: path.resolve(__dirname, './src/main/resources/static/dist')
}
}
When I build npm and run application page contains element <menu-bar></menu-bar> but does not load its content. What could be an issue here?
The problem is that you add the component inside of <div id="vueApp"> at:
<div id="vueApp">
<menu-bar></menu-bar>
</div>
In this case, your app renders inside of this <div id="vueApp"> tag. Everything you write inside of this tag at your html file, will be overwritten.
You have another file named App.vue. You should add your MenuBar.vue component to this main component and it should show.
EDIT: Easiest attempt to get your component to work
This ist the main.js:
import { createApp } from 'vue'
import App from './App.vue'
// Create app
const app = createApp(App);
// Import component
import MenuBar from "./components/MenuBar";
// Use MenuBar
app.component('MenuBar', MenuBar);
// Mount app
app.mount('#app')
This is the App.vue:
<template>
<div>
<MenuBar></MenuBar>
Body
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
This is the MenuBar.vue:
<template>
<div>
Menu
</div>
</template>
<script>
export default {
name: "MenuBar"
}
</script>
As we have a slight different approach I will also give you the package.json, so you can just hit npm install and it should implement all the (few) packages includet in this app:
{
"name": "q68966956",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
It looks like you are in a early stage with your project, so maybe you can start with a stable base from that code. Let me know, if it helped you.

Vue3 Composition API, how to get data from service?

I'm experimenting with the Composition API with Vue3. But there were some points I couldn't find. The same code did not work in two different projects.
What I want to do in my own project is to take the data through the API and use it according to what is required. In short, do the necessary get/post operations. I got this API from Vue's own example.
This is the first project code, package.json and error message
<template>
<div class="home">
<div v-for="datas in data" :key="datas.description">
{{ datas.description }}
</div>
</div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import axios from "axios";
import { ref } from "vue";
#Options({
props: {
msg: String,
},
})
export default class HelloWorld extends Vue {
setup() {
let data = ref([]);
axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json")
.then((res) => {
data.value = res.data.bpi;
});
}
}
</script>
{
"name": "api-project",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-class-component": "^8.0.0-0",
"vue-router": "^4.0.0-0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-typescript": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"typescript": "~4.1.5"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
Vue warn
This is the second project code, package.json, and data
<template>
<div v-for="datas in data" :key="datas.description">
{{ datas.description }}
</div>
</template>
<script lang="ts">
import axios from "axios";
import { ref } from "vue";
export default {
name: "HelloWorld",
setup() {
let data = ref([]);
axios.get("https://api.coindesk.com/v1/bpi/currentprice.json").then((res) => {
data.value = res.data.bpi;
});
return {
data,
};
},
}
</script>
{
"name": "test-api",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"vue": "^3.0.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"typescript": "~4.1.5"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
my data
Could there be an error in my Composition API usage? I've heard that in some videos, "then" is not used for the Composition API. But that's the only way I was able to pull the data from the API.
If my solution is wrong, what method should it be, I'm new at Vuejs can you help?
You need to return the variables from the setup function so that they can be accessed from within the template.
If setup returns an object, the properties on the object can be
accessed in the component's template, as well as the properties of the
props passed into setup:
setup() {
let data = ref([]);
axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json")
.then((res) => {
data.value = res.data.bpi;
});
// return the data as an object
return {
data
}
}
Read more about this in the official vue doc
You can create api dir inside src folder and then inside api dir create a file api.ts and put this code
export async function callApi(endpoint :string, method :string){
return await fetch(endpoint,{
method:method,
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}).then(async response => {
const resData = await response.json()
if (!response.ok) {
// do something to determine request is not okay
resData.isSuccess = false
}
return resData
}).catch(error => {
console.log("callApi in api.ts err")
console.log(error)
throw error
})
}
Go to you component and use this code
<template>
<div v-for="(item,i) in data.records" v-bind:key="i">
{{ item.chartName}}
</div>
</template>
<script>
import {onMounted,reactive} from "vue"
import {callApi} from "#/api/api"
export default{
name:'MyComponent',
setup() {
const data = reactive({
records: [],
})
onMounted( async() =>{
getRecords()
})
const getRecords = async() => {
let resData = await callApi('https://api.coindesk.com/v1/bpi/currentprice.json', 'GET')
data.records = resData
}
return {
data,
}
}
}
</script>
enter code here

Vue3 Testing Library - vue-i18n not loading text

I can't seem to get the following example to work with vue3 and testing library.
https://github.com/testing-library/vue-testing-library/blob/main/src/tests/translations-vue-i18n.js
I've even tried to modify the example like so to get $t to be recognized by injecting messages into a mock but no luck.
Does anyone have an example that works with vue 3?
Here are the details ...
Translations.spec.js
import '#testing-library/jest-dom'
import {render, fireEvent} from '#testing-library/vue'
import Vuei18n from 'vue-i18n'
import Translations from '#/components/Translations'
const messages = {
en: {
Hello: 'Hello!',
message: {
hello: 'Hello!'
}
},
ja: {
Hello: 'こんにちは',
message: {
hello: 'こんにちは'
}
},
}
test('renders translations', async () => {
const {queryByText, getByText} = render(Translations, {
global: {
mocks: {
$t: (messages) => messages
}
}
}, vue => {
// Let's register and configure Vuei18n normally
vue.use(Vuei18n)
const i18n = new Vuei18n({
locale: 'ja',
fallbackLocale: 'ja',
messages,
})
// Notice how we return an object from the callback function. It will be
// merged as an additional option on the created Vue instance.
return {
i18n,
}
})
//expect(getByText('Hello!')).toBeInTheDocument()
//await fireEvent.click(getByText('Japanese'))
expect(getByText('こんにちは')).toBeInTheDocument()
//expect(queryByText('Hello!')).not.toBeInTheDocument()
})
Translations.vue
<template>
<div>
<h2>{{ $t("Hello") }}</h2>
<h2>{{ $t("message.hello") }}</h2>
<button #click="switchLocale('en')">English</button>
<button #click="switchLocale('ja')">Japanese</button>
</div>
</template>
<script>
export default {
name: 'Translations',
methods: {
switchLocale(locale) {
this.$i18n.locale = locale
},
},
}
</script>
package.json
{
"name": "mc",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test:unit": "vue-cli-service test:unit"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.35",
"#fortawesome/free-solid-svg-icons": "^5.15.3",
"#fortawesome/vue-fontawesome": "^3.0.0-4",
"#popperjs/core": "^2.9.2",
"bootstrap": "^5.0.2",
"core-js": "^3.6.5",
"es6-promise": "^4.2.8",
"vue": "^3.1.4",
"vue-hotjar": "^1.4.0",
"vue-i18n": "^9.1.6",
"vue-loader": "^16.2.0",
"vue-router": "^4.0.10",
"vuex": "^4.0.2"
},
"devDependencies": {
"#babel/core": "^7.14.8",
"#babel/preset-env": "^7.14.8",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/vue": "^6.4.2",
"#vue/cli-plugin-babel": "^4.5.13",
"#vue/cli-plugin-eslint": "^4.5.13",
"#vue/cli-plugin-router": "^4.5.13",
"#vue/cli-plugin-unit-jest": "^4.5.13",
"#vue/cli-plugin-vuex": "^4.5.13",
"#vue/cli-service": "^4.5.13",
"#vue/compiler-sfc": "^3.1.4",
"#vue/eslint-config-prettier": "^6.0.0",
"#vue/test-utils": "^2.0.0-rc.9",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-vue": "^7.0.0",
"flush-promises": "^1.0.2",
"prettier": "^2.3.2",
"typescript": "^4.3.5",
"vue-jest": "^5.0.0-alpha.10"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
Error
FAIL tests/unit/Translations.spec.js
● renders translations
TestingLibraryElementError: Unable to find an element with the text: こんにちは. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
<body>
<div>
<div>
<h2>
Hello
</h2>
<h2>
message.hello
</h2>
<button>
English
</button>
<button>
Japanese
</button>
</div>
</div>
</body>
47 | //await fireEvent.click(getByText('Japanese'))
48 |
> 49 | expect(getByText('こんにちは')).toBeInTheDocument()
| ^
50 |
51 | //expect(queryByText('Hello!')).not.toBeInTheDocument()
52 | })
I had the same problem and solved it like this:
I am using the next version of #vue/test-utils and vue-jest ("#vue/test-utils": "^2.0.0-rc.16" + "vue-jest": "^5.0.0-alpha.10").
I created a file called jest.init.js (u can call it anything u like)
import { config } from '#vue/test-utils';
import translations from '#/locales/en';
config.global.mocks = {
$t: (msg) => translations[msg],
};
and then initiate it as setup file in jest.config.js
module.exports = {
...
setupFiles: [
'./tests/unit/jest.init.js',
],
...
};
This answer is for everyone stumbling across that question when using Composition API where there's no global $t to mock.
I've solved it by exporting a function createConfiguredI18n in src/plugins/i18n.ts:
import { createI18n, I18nOptions } from 'vue-i18n'
import deDE from '#/locales/de-DE.json'
import enUS from '#/locales/en-US.json'
// Type-define 'de-DE' as the master schema for the resource
type MessageSchema = typeof deDE
export function createConfiguredI18n(locale: string, fallbackLocale: string) {
return createI18n<I18nOptions, [MessageSchema], 'de-DE' | 'en-US'>({
locale: locale || 'en-US',
fallbackLocale: fallbackLocale || 'en-US',
messages: {
'de-DE': deDE,
'en-US': enUS,
},
})
}
export const i18n = createConfiguredI18n('de-DE', 'en-US')
Then in the unit test you can do the following to initialize vue-i18n with your translations:
import {flushPromises, mount, VueWrapper} from '#vue/test-utils'
import {nextTick} from 'vue'
import {createConfiguredI18n} from '#/plugins/i18n'
...
describe('SubjectUnderTest', () => {
it('should display translation "FooBar"', async () => {
const locale = 'de-DE'
const fallbackLocale = 'en-US'
const wrapper = await createWrapper({locale, fallbackLocale})
...
}
async function createWrapper(options: {
locale: string
fallbackLocale: string
}): Promise<VueWrapper> {
const i18n = createConfiguredI18n(options.locale, options.fallbackLocale)
const wrapper = mount(sut, {
global: {
plugins: [i18n],
},
})
await nextTick()
await flushPromises()
return wrapper
}
}
If you don't want the translations but instead mock them and check for the keys only, you can do the following in your unit test instead:
import {flushPromises, mount, VueWrapper} from '#vue/test-utils'
import {nextTick} from 'vue'
import {i18n} from '#/plugins/i18n'
...
i18n.global.t = (key) => key
describe('SubjectUnderTest', () => {
it('should display translation for key "foo.bar"', async () => {
const wrapper = await createWrapper()
...
}
async function createWrapper(): Promise<VueWrapper> {
const wrapper = mount(sut, {
global: {
plugins: [i18n],
},
})
await nextTick()
await flushPromises()
return wrapper
}
}

Why am I getting "Cannot find module..." Typescript error for ".vue" file on webpack-dev-server recompilation?

I've setup a small webpack project which creates a Vue app bundle which is included in a static HTML file where the app is injected. I want to have components written in Typescript so I've included ts-loader in the webapck configuration. The build process - using the "webpack" command - works ok, but I'm having some trouble when I use webpack-dev-server.
When I initially start the server, everything works fine: the bundle is created and served on my local server and the browser displays the app correcly. However, when I make a change in the source code and save, I get a Typescript error when the code is recompiled telling me that a module or declaraton is missing for the ".vue" file for my component:
TS2307: Cannot find module './components/Banner.vue' or its corresponding type declarations.
To start the server I use the following command:
webpack serve --open
Project's folder structure
=======
webpack.config.js
const { VueLoaderPlugin } = require('vue-loader')
const path = require('path')
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: {
app: './src/app.js',
},
output: {
filename: '[name].bundle.js',
},
plugins: [
new VueLoaderPlugin(),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.vue$/,
use: ['vue-loader']
},
{
test: /\.ts$/,
loader: 'ts-loader',
exclude: [/node_modules/],
options: { appendTsSuffixTo: [/\.vue$/] }
},
],
},
}
app.js
import Vue from 'vue'
import App from './App.vue'
const app = new Vue({
render: (h) => h(App)
})
app.$mount('#app')
App.vue
<template>
<div id="app">
<h1>{{ welcomeMessage }}</h1>
<Banner />
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Banner from './components/Banner.vue'
export default Vue.extend({
components: {
Banner,
},
data: () => ({
welcomeMessage: 'Hello world!'
})
})
</script>
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"strict": true,
"module": "es2015",
"moduleResolution": "node"
}
}
#types/vue-shims.d.ts
declare module "*.vue" {
import Vue from 'vue'
export default Vue
}
package.json
{
"name": "2021-06-21-webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"dev": "webpack serve --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^8.3.0",
"typescript": "^4.3.4",
"vue-loader": "^15.9.7",
"vue-template-compiler": "^2.6.14",
"webpack": "^4.46.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"vue": "^2.6.14"
}
}