...mapState SyntaxError in Vue.js, with vuex - vue.js

when I'm using ...mapState in vue.js, I ran into an error when bundling files with webpack. The error is
Module build failed: SyntaxError: Unexpected token.
I've tried kinds of babel plugins such as stage-0 and transform-object-rest-spread.
Howerver, none seems to be ok for me. Would you please so kind tell me how to solve it?
the source code is
<script type="text/babel">
import { mapState } from 'vuex';
let [a, b, ...other] = [1,2,3,5,7,9]; // this line is ok
console.log(a);
console.log(b);
console.log(other);
export default{
computed:{
localComputed(){
return 10;
},
...mapState({ //this line caused the error
count: state => state.count
})
},
methods: {
increment() {
this.$store.commit('increment');
},
decrement() {
this.$store.commit('decrement');
}
}
}
</script>
and this is the webpack config fragment
{
test: /\.(js|es|es6|jsx)$/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['react'],
['es2015', {modules: false, loose: true}],
['stage-2']
],
plugins: [
['transform-runtime'],
// https://github.com/JeffreyWay/laravel-mix/issues/76
['transform-object-rest-spread'],
['transform-es2015-destructuring']
],
comments: false,
cacheDirectory: true
}
},
{
loader: 'eslint-loader',
options: {
configFile: eslintConfigPath
}
}
],
exclude: excludeReg
}

I had a similar problem a while ago. As far as I can see, your issue is that your babel-loader does not currently work on .vue files (which is correct as such).
The vue-loader, which handles .vue files, uses babel internally as well, but it won't use webpack's babel-loader config. The easiest way to provide a config for babel in the vue-loader is (unfortunately) creating a separate .babelrc file with your babel config in the root folder of your project:
.babelrc
{
presets: [
["react"],
["es2015", { "modules": false, "loose": true}],
["stage-2"]
],
plugins: [
["transform-runtime"],
["transform-object-rest-spread"],
["transform-es2015-destructuring"]
]
}
Note that .babelrc requires valid JSON.

Related

Can't compile sass while using Vue Storybook

I'm trying to create storybook on vue. My components written using sass. So, I made this in .storybook/main.js:
webpackFinal: (config) => {
config.module.rules.push({
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
})
return config
}
And the styles looks like this:
<style lang="sass" scoped>
button
background-color: red
</style>
So I'm getting this error when trying to compile:
SassError: Invalid CSS after "": expected 1 selector or at-rule, was "button"
on line 1 of C:\Code\testproj\src\components\UI\TestComponent.vue
And if I change my style to this:
<style lang="sass" scoped>
button {
background-color: red
}
</style>
All works, but that's not a sass syntax.
I was having this exact same issue and I was able to solve it. The issue is from the webpack config. If you're using SASS, your webpack.config.js file in your .storybook folder should look like this:
module.exports = ({ config }) => {
config.module.rules.push({
test: /\.sass$/,
use: [
require.resolve("vue-style-loader"),
require.resolve("css-loader"),
{
loader: require.resolve("sass-loader"),
options: {
sassOptions: {
indentedSyntax: true
}
}
}
],
});
return config;
};
And if you're using SCSS, then it should be like this:
module.exports = ({ config }) => {
config.module.rules.push({
test: /\.scss$/,
use: [
require.resolve("vue-style-loader"),
require.resolve("css-loader"),
require.resolve("sass-loader"),
],
});
return config;
};
I was able to figure this out while reading the Vue Loader Docs
The problem is that in your webpack config, you are telling webpack that only use sass-loader when de extension of your file was test: /.s[ac]ss$/i That is to say .sass or .scss. However the extension of your file is .vue, because you are using sass in the vue file of your component.
With that configuration, try to put your sass style in a .sass file and check if works
For anyone using React 17+ with Storybook 6.4.9+, I had a similar problem where the Storybook/webpack build was not including my SCSS files. This configuration in .storybook/main.js worked for me:
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
],
"framework": "#storybook/react",
webpackFinal: async (config) => {
// add SCSS support for CSS Modules
config.module.rules.push({
test: /\.scss$/,
use: [
require.resolve("style-loader"),
require.resolve("css-loader"),
require.resolve("sass-loader"),
],
});
return config;
}
}
I spend a lot of time to find better solution. It is may main.js config file for Storybook 6.4.9:
const path = require('path');
module.exports = {
"stories": [
"../src/**/*.stories.#(js|jsx|ts|tsx|mdx)"
],
"addons": [
"#storybook/addon-essentials",
"#storybook/addon-actions",
"#storybook/addon-controls",
"#storybook/addon-links",
{
name: '#storybook/preset-scss',
options: {
sassLoaderOptions: {
implementation: require('node-sass'), // ATTENTION: We need to use "node-sass" instead "sass/dart-sass"
sassOptions: {
indentedSyntax: true
},
},
}
},
"#storybook/addon-postcss",
],
"framework": "#storybook/vue",
features: {
babelModeV7: true,
},
webpackFinal: async (config, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
// ATTENTION: Need to preload "global.sass" style for all elements;
config.module.rules.map(rule => {
if (rule.test instanceof RegExp && rule.test.toString() === '/\\.s[ca]ss$/') {
rule.use.push({
loader: require.resolve('sass-resources-loader'),
options: {
resources: [
path.resolve(__dirname, '../src/styles/global.sass')
]
}
})
}
return rule
})
// ATTENTION: Need to compile "Pug" templates.
config.module.rules.push(
{
test: /\.pug$/,
oneOf: [
// this applies to `<template lang="pug">` in Vue components
{
resourceQuery: /^\?vue/,
use: ['pug-plain-loader']
},
// this applies to pug imports inside JavaScript
{
use: ['raw-loader', 'pug-plain-loader']
}
]
}
);
// Return the altered config
return config;
},
}

vue file dont working in atom IDE with webpack

I'm creating a project in Rails with vue, for this I'm working with webpack, what happens and my text editor, atom IDE, does not process the .vue files, I've tried the steps that the documentation recommends, but I do not know what I'm doing wrong
I provided loading the vue-loader by npm, but I still can not see the .vue files in my project, then I did it by configuring in the webpack.config.js file, and nothing. Then I leave the links of the things I did that did not work.
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import OptimizeCssAssetsPlugin from '../../../src/';
module.exports = {
entry: './index',
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: { loader: 'style-loader' },
use: {
loader: 'css-loader',
options: { minimize: true }
}
},
vue: {
loaders: {
sass: 'style!css!sass?indentedSyntax',
scss: 'style!css!sass'
}
},
plugins: [
new ExtractTextPlugin('file.css'),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /optimize-me\.css/g
})
};
I hope to be able to work the .vue files

Webpack + vue-loader + postcss-modules results in empty $style object

In my app I'm initializing a Vue app, which uses single file .vue components.
I use Webpack to bundle, and vue-loader + postcss-modules to generate scoped classes.
But for some reason I can't access the generated classes inside my components ($style object is empty). I'll explain the problem below and created this repo as an example.
My hello.vue component looks like this:
<template>
<div :class="$style.hello">
Hello World!
</div>
</template>
<script>
export default {
name: "hello",
created() {
console.log(this.$style); // <- empty object :(
}
};
</script>
<style module>
.hello {
background: lime;
}
</style>
hello.vue.json is generated as expected (CSS Modules mapping):
{"hello":"_hello_23p9g_17"}
Scoped styles are appended in the document head, and when using mini-css-extract-plugin it is bundled in app.css:
._hello_23p9g_17 {
background: lime;
}
Does anyone know what the problem is and possibly how to fix this?
Below my config files.
webpack.config.js (trimmed for readability)
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
module.exports = {
entry: {
app: "./src/index.js"
},
output: {
filename: "[name].js",
path: path.resolve(__dirname, "build")
},
resolve: {
extensions: [".js", ".vue", ".json", ".css"],
alias: {
vue: "vue/dist/vue.esm.js"
}
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "babel-loader"
}
},
{
test: /\.vue$/,
loader: "vue-loader"
},
{
test: /\.css$/,
use: [
"vue-style-loader",
// MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
// modules: true,
importLoaders: 1
}
},
"postcss-loader"
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css"
}),
new VueLoaderPlugin()
]
};
postcss.config.js
module.exports = {
ident: "postcss",
plugins: {
"postcss-preset-env": { stage: 0 },
"postcss-modules": {}
}
};
EDIT:
FYI, setting modules: true in the css-loader options works in that it populates the $style object (see docs):
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: true
}
}
]
}
But in our app we use postcss-loader (as per docs) that takes care of all transformations including scoping. Enabling both modules: true and postcss-modules conflicts and breaks the classes/mapping (as expected).
In other words, I'm looking for a way to omit the modules: true option and enable css modules using postcss-modules instead.
Found a workaround: manually import the styles from the JSON file.
If anyone knows a better way please let me know :)
hello.vue.json
{"hello":"_hello_fgtjb_30"}
hello.vue
<template>
<div :class="style.hello">
Hello World!
</div>
</template>
<script>
import style from "./hello.vue.json";
export default {
name: "hello",
beforeCreate() {
this.style = style;
},
created() {
console.log(this.style);
}
};
</script>
<style module>
.hello {
background: lime;
}
</style>
This only works when using postcss-modules (loaded from config by postcss-loader in my case) instead of using modules: true:
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
importLoaders: 1
}
},
"postcss-loader"
]
};
See this PR as a full example.

Vue of Typescript. Error: Module not found: Error: Can't resolve './components/mycomponent.vue'

I am using vue of typescript as well as typescript in Express. Everything worked until i want to use single file component in vue.js.
Here is my component,
<template>
<div>This is a simple component. {{msg}}</div>
</template>
<script lang='ts'>
export default {
data() {
return {
msg: "you"
}
}
}
</script>
My webpack file,
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
const Webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
bundle: [
'./node_modules/bootstrap/dist/js/bootstrap.js',
'./dist/web/views/common/client/ts/_main.js',
'./web/views/common/client/style/main.scss'
]
},
output: {
path: path.resolve(__dirname, 'public'),
filename: '[name].js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
ts: 'ts-loader'
},
esModule: true
}
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{
loader: 'css-loader',
options: {
minimize: false
}
}, {
loader: 'sass-loader'
}]
})
},
{
test: require.resolve('jquery'),
loader: 'expose-loader?$!expose-loader?jQuery'
}
]
},
resolve: {
alias: {
vue$: 'vue/dist/vue.esm.js'
}
},
plugins: [
new ExtractTextPlugin('styles.css'),
new HtmlWebpackPlugin({
template: './web/views/common/_layout.pug',
filename: '../web/views/common/layout.pug',
filetype: 'pug'
}),
new HtmlWebpackPugPlugin(),
new Webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
Popper: 'popper.js'
})
]
};
If I don't use single file component, everything works, but when i introduce .vue file, it will show this error,
ERROR in ./dist/web/views/about/client/ts/_aboutController.js
Module not found: Error: Can't resolve './components/mycomponent.vue' in '/Users/george/github/bochure/dist/web/views/about/client/ts'
# ./dist/web/views/about/client/ts/_aboutController.js 4:24-63
# ./dist/web/views/common/client/ts/_main.js
# multi ./node_modules/bootstrap/dist/js/bootstrap.js ./dist/web/views/common/client/ts/_main.js ./web/views/common/client/style/main.scss
Can anyone help me? You can also download my source at github and help me out. Many thanks.
git#github.com:geforcesong/bochure.git
I'd suggest you to check the component path first.
If you are embedding one vue component into another then check if both are on the same directory level.
If they are then you can use './component-name.vue' and you will be good to go.
Try to change
'./components/mycomponent.vue'
'../components/mycomponent.vue'
This might work in some cases.

Webpack with babel-loader not emitting valid es5

I have a webpack config that is based off https://github.com/vuejs-templates/webpack-simple/blob/master/template/webpack.config.js
It uses vue-loader and babel-loader. The issue is I cannot get it to generate ES5 code so that it will work in the most broad range of clients.
If I use the ES2015 preset, webpack.optimize.UglifyJsPlugin fails to minify the output because Uglify can only handle ES5 (not counting the harmony branch). The errors are similar to: Unexpected token: punc (() and occur in multiple files.
I can work around this by using babili-webpack-plugin which will minify the ES6 code but is very slow. However, when I deploy this code, I see errors being reported back saying Block-scoped declarations (let, const, function, class) not yet supported outside strict mode so I know they are older clients choking on ES6 code.
How can I get proper ES5 code output from babel-loader? I have tried multiple presets, with or without the transform-runtime plugin. Config below:
const webpack = require('webpack');
const globEntries = require('webpack-glob-entries');
const _ = require('lodash');
const path = require('path');
const BabiliPlugin = require("babili-webpack-plugin");
const env = process.env.NODE_ENV;
let entries;
if (env === 'production') {
entries = globEntries('./src/**/vue/*.js');
} else {
entries = _.mapValues(globEntries('./src/**/vue/*.js'), entry => [entry, 'webpack-hot-middleware/client?reload=true']);
}
module.exports = {
entry: entries,
output: {
path: '/', ///no real path is required, just pass "/"
publicPath: '/vue',
filename: '[name].js',
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
scss: 'vue-style-loader!css-loader!sass-loader',
sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
},
// other vue-loader options go here
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
query: {
presets: ['es2015'],
plugins: ['transform-runtime'],
},
},
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
},
},
],
},
resolve: {
alias: {
vue$: 'vue/dist/vue.esm.js',
},
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // Enable HMR
new webpack.NoEmitOnErrorsPlugin(),
],
performance: {
hints: false,
},
devtool: '#eval-source-map',
};
if (env === 'staging' || env === 'production') {
//module.exports.devtool = env === 'staging' ? '#source-map' : false;
module.exports.devtool = '#source-map';
module.exports.output.path = path.resolve(__dirname, './src/v1/parse/cloud/public/vue');
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: `"${env}"`,
},
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false,
},
}),
// new BabiliPlugin(),
new webpack.LoaderOptionsPlugin({
minimize: true,
}),
]);
}
vue-loader will process your js with babel-loader (if it's detected), and uses .babelrc by default.
In your current setup you are not passing any options to Babel when it is used by vue-loader (meaning Babel uses no rules for your Vue files).
Either create .babelrc or specify the js loader by yourself for the .vue files to provide it with options:
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
js: 'babel?presets[]=es2015' // Pass parameters as options
}
}
}
The env preset for Babel has an uglify option that will fully compile to ES5. This preset is recommended practice to keep your environment up to date.
// .babelrc
{
"presets": [
[ "env", { "uglify": true } ],
"stage-1" // Or other presets not included with 'env' preset.
],
"plugins": ["transform-runtime"]
}
Instead of using preset es2015 only, you might add es2016 and es2017, as well as stage-4, stage-3, etc. to assure all your code is transformed, and not just the ES2015 parts.
Nothing wrong with answer here already, but here is a solution that does not require a .babelrc file. This answer works for a standalone webpack.config.js file. I got this answer from taking a look under the hood of the laravel-mix library.
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders:{
js: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
['env', {
'modules': false,
'targets': {
'browsers': ['> 2%'],
uglify: true
}
}]
],
plugins: [
'transform-object-rest-spread',
['transform-runtime', {
'polyfill': false,
'helpers': false
}]
]
}
},
}
}
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
I spent the better part of a day reading up all these useless blogs omit the core concept that babel-loader has to be attached to the vue-loader.