Background:
I added TypeScript support to my existing project, so I added ts-loader and typescript. I think, I configured everything right and it is working fine in dev and prod mode.
I would like to update gradually, keeping all the JavaScript code in place and using TypeScript for everything new or where there is a need for refactoring. So it may be important to note that TableValue.vue is an old js component.
Problem:
Edit: It also occurs with npm run watch
When I run npm run hot in package.json: "scripts": { ..., "hot": "mix watch --hot", ...} it only works on the first try. As soon as I change any file and trigger a recompile, I get:
√ Mix: Compiled successfully in 19.15s
webpack compiled successfully
// Here the recompile is triggered
i Compiling Mix
√ Mix: Compiled with some errors in 509.01ms
ERROR in C:\fakepath\resources\js\components\test\component.vue.ts
24:23-41
[tsl] ERROR in C:\fakepath\resources\js\components\test\component.vue.ts(24,24)
TS2307: Cannot find module './TableValue.vue' or its corresponding type declarations.
webpack compiled with 1 error
I suspect that this error comes from ts-loader, but why is everything working on the first try?
I could just ignore this error, but then hot module replacement is unusable, because I have to manually trigger a new build process every time anyway.
Has someone got such an setup working?
What can I do to solve this error?
Infos:
I'm working with:
Laravel 8.58
Laravel Mix 6.0.25
Vue 2.6.14
ts-loader 9.2.5
typescript 4.4.2
Here the script tag from the test component:
<script lang="ts">
import Vue, { PropType } from 'vue';
import TableValue from "./TableValue.vue";
import Model from "#/js/types/model.js";
export default Vue.extend({
name: "TestComponent",
components: {
TableValue
},
props: {
'model': {
type: Object as PropType<Model>,
required: true
}
},
data() {
return {};
},
});
</script>
Project Structure:
app/
bootstrap/
config/
database/
node_modules/
public/
resources/
js/
components/
store/
types/
views/
app.js
bootstrap.js
routes.js
shims-vue.d.ts
lang/
sass/
views/
routes/
storage/
tests/
vendor/
composer.json
composer.lock
tsconfig.json
package-lock.json
package.json
phpunit.xml
vs.code-workspace
webpack.mix.js
webpack.mix.js:
const mix = require('laravel-mix');
const ResolveTypeScriptPlugin = require("resolve-typescript-plugin").default;
mix.webpackConfig({
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
options: { appendTsSuffixTo: [/\.vue$/] },
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.ts', '.vue'],
alias: {
'#': __dirname + '/resources'
},
fullySpecified: false,
plugins: [new ResolveTypeScriptPlugin()]
},
devtool: 'source-map'
}).sourceMaps();
mix.ts('resources/js/app.js', 'public/js')
.sass('resources/sass/app.sass', 'public/css').sourceMaps()
.vue();
mix.extract();
tsconfig.json:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"noImplicitAny": false,
"importHelpers": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"allowJs": true,
"checkJs": false,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"#/*": [
"resources/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"files": [
"resources/js/shims-vue.d.ts"
],
"include": [
"resources/js/**/*.ts",
"resources/js/**/*.vue",
],
"exclude": [
"node_modules",
".vscode",
"app",
"bootstrap",
"config",
"database",
"public",
"routes",
"storage",
"tests",
"vendor"
]
}
Update:
When I remove shims-vue.d.ts, I get the error immediately.
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
It looks like this file is only read/applyed once and not after? Not sure.
It looks like ts-loader doesn't support HMR yet.
https://github.com/TypeStrong/ts-loader#hot-module-replacement
I installed fork-ts-checker-webpack-plugin and updated webpack.mix.js to:
const mix = require('laravel-mix');
const path = require('path');
const ResolveTypeScriptPlugin = require("resolve-typescript-plugin").default;
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
mix.webpackConfig({
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/],
transpileOnly: true
},
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.ts', '.tsx', '.vue'],
alias: {
'#': path.resolve(__dirname + '/resources'),
'#store': path.resolve(__dirname + '/resources/js/store'),
'#components': path.resolve(__dirname + '/resources/js/components')
},
fullySpecified: false,
plugins: [new ResolveTypeScriptPlugin()]
},
plugins: [new ForkTsCheckerWebpackPlugin()],
devtool: 'source-map'
}).sourceMaps();
mix.ts('resources/js/app.js', 'public/js')
.sass('resources/sass/app.sass', 'public/css').sourceMaps()
.vue();
mix.extract();
Now everything is working fine but I'm still not sure why watch was also affected and where exactly the problem was.
I'm not using Typescript, but the same thing was happening to me, when i ran npm run watch/hot where only successful on the first change of the code, then, you can not see the changes until you run npm run watch/hot or npm run dev again. The strange thing was that everything was compiling successfully on every change I made.
I manage to debug it with git, and found out that I was importing a component with a wrong name but did not get an error on the console.
My component name was WhosApplying.vue
I got:
import WhosApplying from "#/whosApplying.vue"
And change it for:
import WhosApplying from "#/WhosApplying.vue";
That mistake in the w instead of W make me lose hours. 😅
I ran into this using laravel-mix after adding typescript to an Inertia / Vue 3 project.
Using Volar (Not Vuter)
To fix it I changed my webpack.config.js file from:
const path = require('path');
module.exports = {
resolve: {
alias: {
'#': path.resolve('resources/js'),
},
},
};
to:
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/],
transpileOnly: true
},
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.ts', '.tsx', '.vue'],
alias: {
'#': path.resolve(__dirname + '/resources/js'),
},
},
};
Related
I am getting an error when starting a dev server:
Error: EPERM: operation not permitted, scandir '/var/www/html/rootfs/host_mnt/c
I have a Laravel - Inertia - Vue3 application that I am trying to build with Vite for development.
From vite.config.js
import {defineConfig} from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '#vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
]
});
devcontainer.json
{
"name": "Mangrove Development Environment",
"dockerComposeFile": [
"../docker-compose.yml"
],
"service": "mangrove",
"workspaceFolder": "/var/`your text`www/html",
"settings": {},
"customizations": {
"vscode": {
"extensions": [
"felixfbecker.php-debug",
"ms-vsliveshare.vsliveshare",
"eamodio.gitlens",
"bmewburn.vscode-intelephense-client",
"mikestead.dotenv",
"amiralizadeh9480.laravel-extra-intellisense",
"ryannaddy.laravel-artisan",
"onecentlin.laravel5-snippets",
"onecentlin.laravel-blade",
"EditorConfig.EditorConfig",
"jcbuisson.vue",
"redhat.vscode-yaml"
]
}
},
"remoteUser": "sail",
//"postCreateCommand": "chown -R 1000:1000 /var/www/html"
"postCreateCommand": ""
// "forwardPorts": [],
// "runServices": [],
// "shutdownAction": "none",
}
I tried using "postCreateCommand": "chown -R 1000:1000 /var/www/html" in the devcontainer.json file, but this simply tries to turn over ownership of every single file on my Windows system's hard drive.
I have also tried inserting
server: {
watch: {
ignored: [
"rootfs/**/*",
],
}
}
Into the vite.config.js to perhaps ignore those files.
I am trying to compile my ES6+ code to vanilla js using Grunt task runner.
I have purposely chosen Grunt over webpack and gulp because I just wanted to minify my js files.
I have successfully compiled my ES6 code to vanilla after running the code got an error saying generatorRuntime is not defined. After analysing the issue I could that my async and await code is giving the issue after it gets converted to vanilla js.
I have my code snippet of my gruntfile.js and package.json.
babel: {
options: {
sourceMap: true
},
dist: {
files: [{
"expand": true,
"cwd": "./htdocs/js/src",
"src": ["**/*.js"],
"dest": "./htdocs/js/compiled/",
"ext": ".js"
}]
}
},
//uglify will minify all the js files in js/src folder.
uglify: {
all_src : {
options : {
sourceMap : true
},
files: [{
expand: true,
flatten: true,
cwd:'./htdocs/js/compiled',
src: '**/*.js',
dest: './htdocs/js/dist',
ext: '.min.js'
}]
}
}
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-contrib-uglify');
Package.json
"devDependencies": {
"babel-core": "^6.26.3",
"babel-preset-latest": "^6.24.1",
"grunt": "^1.1.0",
"grunt-babel": "^7.0.0",
"grunt-cli": "^1.3.2",
"grunt-contrib-uglify": "^4.0.1"
},
"babel": {
"presets": [
"latest"
]
}
That's probably because the polyfills aren't getting shipped in your bundle. In your babel.options object inside Gruntfile, you can set
presets: [['#babel/preset-env', { useBuiltIns: 'usage', corejs: 3 }]]
and don't forget to include corejs as dependency in your project.
npm install core-js --save
I want to use typescript in Vue in Laravel project.
I already checked all tutorials for that but none of them works for me give below
teej.
Titas Gailius.
sebastiandedeyne.
when ever i run 'npm run dev' i get this error
ERROR in ./resources/js/app.ts
Module build failed: Error: You may be using an old version of webpack; please check you're using at least version 4
at successfulTypeScriptInstance (E:\PersonalProjects\web_dev\blog\node_modules\ts-loader\dist\instances.js:144:15)
at Object.getTypeScriptInstance (E:\PersonalProjects\web_dev\blog\node_modules\ts-loader\dist\instances.js:34:12)
at Object.loader (E:\PersonalProjects\web_dev\blog\node_modules\ts-loader\dist\index.js:17:41)
# multi ./resources/js/app.ts ./resources/sass/app.scss
Im facing this problem from quite some days but i was finally be able to find the solution for that so im Sharing my exp to folks who want to use typescript instead of javascript in vue in laravel. so here is the instruction
here the intruction
Laravel 5.7 uses Laravel-mix which down the line uses webpack 3 . Which is not what we want for typescript to work in laravel project.
Initialize your project
Let's create a new Project. You can also do this on Existing project just make sure to convert js code to ts.
First make sure you have composer and laravel installed
sh
laravel new Laravel-Vue-Typecript
Open the project in your any favraite code editor.
Open the package.json and add these packages to devdependencies
{
"devDependencies": {
"auto-loader": "^0.2.0",
"autoprefixer": "^9.4.1",
"axios": "^0.18",
"bootstrap": "^4.0.0",
"lodash": "^4.17.5",
"popper.js": "^1.12",
"jquery": "^3.2",
"cross-env": "^5.1",
"css-loader": "^1.0.1",
"mini-css-extract-plugin": "^0.4.5",
"node-sass": "^4.10.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"ts-loader": "^5.3.1",
"typescript": "^3.2.1",
"uglifyjs-webpack-plugin": "^2.0.1",
"vue": "^2.5.17",
"vue-class-component": "^6.3.2",
"vue-property-decorator": "^7.2.0",
"webpack": "^4.26.1",
"webpack-cli": "^3.1.2",
"vue-loader": "^15.4.2",
"vue-template-compiler": "^2.5.17"
}
}
Now install these npm packages with
npm install
Add Typescript Support
Then rename these files
Laravel-Vue-Typecript/
├─ resources/js/app.js => resources/js/app.ts
└─ resources/js/bootstrap.js => resources/js/bootstrap.ts
Now Change the Code in app.ts, bootstrap.ts and
resources/js/components/ExampleComponent.vue
// app.ts
import "./bootstrap"
import Vue from "vue"
import ExampleComponent from "./components/ExampleComponent.vue"
Vue.component('example', ExampleComponent)
new Vue({
el: '#app'
})
// bootstrap.ts
import axios from 'axios';
import * as _ from 'lodash';
import jQuery from 'jquery';
import * as Popper from 'popper.js';
import 'bootstrap';
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token : HTMLMetaElement | null = document.head!.querySelector('meta[name="csrf-token"]');
if (token) {
axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
// resources/js/components/ExampleComponent.vue
<template>
<h1>This is an example component</h1>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from "vue-class-component"
#Component
export default class ExampleComponent extends Vue {
mounted() : void {
console.log("hello");
}
}
</script>
```
Create typings.d.ts file inside resources/js and add these lines.
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
declare module 'jquery';
declare module 'lodash';
Now Create tsconfig.json, webpack.config.js and postcss.config.js in the root of your project and these lines of code to them respectivly
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"strict": true,
"module": "es2015",
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true
},
"include": [
"resources/js/**/*"
],
"exclude": [
"node_modules",
"vendor"
]
}
webpack.config.json
const path = require('path')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
let env = process.env.NODE_ENV
let isDev = env === 'development'
const WEBPACK_CONFIG = {
mode: env,
entry: {
app: ['./resources/js/app.ts', './resources/sass/app.scss'],
},
output: {
publicPath: './public',
path: path.resolve(__dirname, 'public'),
filename: 'js/[name].js',
chunkFilename: 'js/chunks/app.js'
},
module: {
rules: [{
test: /\.tsx?$/,
loader: 'ts-loader',
options: { appendTsSuffixTo: [/\.vue$/] },
exclude: /node_modules/,
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
],
exclude: /node_modules/,
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css'
}),
new VueLoaderPlugin(),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer()
]
}
})
],
resolve: {
extensions: ['.js', '.jsx', '.vue', '.ts', '.tsx'],
alias: {
vue$: 'vue/dist/vue.esm.js',
},
},
optimization: {
splitChunks: {
chunks: 'async',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
}
if (!isDev) {
WEBPACK_CONFIG.optimization = {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true
}),
new OptimizeCSSAssetsPlugin({})
]
}
WEBPACK_CONFIG.plugins.push(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: 'production'
}
})
)
}
module.exports = WEBPACK_CONFIG
postcss.config.js
module.exports = {
plugins: {
'autoprefixer': {}
} }
Now finally change the "scripts" in package.json
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=webpack.config.js"
},
Finally build the project
and run the npm scripts by
npm run dev // To build the Project
npm run watch // To build and watch for files changes and build automagically
npm run prod // for production
I've been looking over the docs and checking other people's questions but I can't find the simple answer to how to compile all my sass down to a simple css file and specify the directory I want the resulting css file to output to.
For quick context:
I have a public directory with a stylesheets directory and a build directory in it. webpack compiles the app into build, and I'd like to have the sass compile style.css into the stylesheets directory.
Here's a screenshot of my public directory:
public dir img
I'd like to be able to do something like this in my webpack.config.js (only showing pertinent code for brevity):
const ExtractTextPlugin = require('extract-text-webpack-plugin');
...
// To be called in plugins:
const cssOutput = new ExtractTextPlugin('./public/stylesheets/style.css');
inside module loaders:
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader'),
},
In plugins:
plugins: [
.
.
.
cssOutput,
],
I'd like to be able to access the output file with this line in my index.html file located in the public directory:
<link rel="stylesheet" href="/stylesheets/style.css" />
I'm currently doing this using gulp and it works fine, I'm just trying to transition everything into webpack. Any help would be greatly appreciated!
Turns out you can just set the output file like this:
const cssOutput = new ExtractTextPlugin('../stylesheets/style.css', { allChunks: true });
I made the noob mistake of forgetting to add:
require('_scss/style.scss');
in my index.jsx file.
For anyone who runs into this issue, I still had trouble with fonts and images, so inside module loaders in the webpack.config.js I had to add:
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/,
loader: 'file',
},
and since this output everything into my build directory, I just changed the css to output everything in the build directory as well to prevent path errors. I changed it to this:
const cssOutput = new ExtractTextPlugin('style.css', { allChunks: true });
Hopefully this helps someone else who runs into this type of issue!
Work for Me::
webpack.config.js
module.exports = {
entry: ['./src/app.ts', './src/sass/style.scss'],
module:{
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
include: [path.resolve(__dirname, 'src', 'src/class')]
},
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options: {
name: '/css/[name].css'
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader?-url'
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
],
include: [path.resolve(__dirname, 'src/sass')]
}
]
},
output: {
filename: 'js/app.js',
path: path.resolve(__dirname, 'public')
}
}
postcss.config.js
module.exports = {
plugins: {
'autoprefixer': {}
}
}
package.json
{
"name": "tsscript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"nov": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.8.5",
"css": "^3.0.0",
"css-loader": "^3.6.0",
"extract-loader": "^5.1.0",
"postcss-loader": "^3.0.0",
"sass": "^1.26.10",
"sass-loader": "^9.0.2",
"style-loader": "^1.2.1",
"ts-loader": "^8.0.0",
"typescript": "^3.9.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
}
}
Directory Snap:
Have you take a look at https://www.npmjs.com/package/extract-text-webpack-plugin?
you'll probably need it.
Recent solution, you can use mini-css-extract-plugin, css-loader, and sass-loader. mini-css-extract-plugin can create a CSS file per JS file which contains CSS.
Install dependencies:
npm i -D mini-css-extract-plugin css-loader sass-loader
For example, your main JS file that includes a style is ./src/index.js:
...
import './src/style.scss';
...
Configure webpack.config.js:
...
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
...
entry: {
main: './src/index.js',
},
plugins: [
new MiniCssExtractPlugin(),
],
...
module: {
rules: [
...
{
test: /\.s[ac]ss$/i,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
...
]
},
resolve: {
modules: ["node_modules", path.resolve(__dirname, "src")],
extensions: ['.js', '.scss', ...]
}
}
Then, you can check your output directory, there will be main.css. The plugin set default name to [name].css (entry name).
What is the best way to trigger Webpack build after deploying to Heroku?
Push already bundled version in not the most beautiful solution.
What kind of application is this? If you are using a package.json, you could run webpack in the postinstall step using npm scripts.
I have solved this issue by placing devDependencies in normal dependencies, and I changed the postinstall script to:
node_modules/.bin/webpack
You can set postinstall in your package.json to the following NODE_ENV=production webpack -p
Then set start to node
But you will need to make sure to config your webpack for production either by setting it within your webpack.config.js or webpack.config.js(production) as a production config.
I set everything within my webpack.config.js as follows..
const path = require('path');
const webpack = require('webpack');
const debug = process.env.NODE_ENV !== "production";
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: path.resolve(__dirname, 'src'),
filename: 'bundle.js'
},
devtool: debug ? "inline-sourcemap" : null,
module: {
loader: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['angular']
}
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}]
},
devServer: {
historyApiFallback: true,
contentBase: 'src'
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: {except: ['$', 'exports', 'require', 'app']},
compress: {warnings: false},
sourceMap: false
})
]
}
so basically, once the command runs npm run postinstall bundle will be generated in the directory as per webpack.config.js (output). But remember to include in your package.json with the commands NODE_ENV=production webpack -p before running 'npm start'. See example below..
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "./src/bundle.js",
"engines": {
"node": "6.4.0"
},
"scripts": {
"start": "node ./src/server.js",
"postinstall": "NODE_ENV=production webpack -p"
},
"author": "",
"license": "ISC",
"dependencies": ...