nuxtjs issue with IE11 compatibility_ object assign - vue.js

I am suffered by IE compatibility. (my vue version is 3.1.0, nuxt is 2.3.4)
It keeps error with Object.assign. Here is the list what I have tried.
babel-preset-vue-app(https://www.npmjs.com/package/babel-preset-vue-app). Heard that it does not support vue2.X. I followed the description on this post. It gets an error while building source.
Adding babel-polyfill in nuxt.config.js. It does not error, but still I got Object.assign error on the page.
Install babel/plugin-transform-object-assign. It also does not make any error in build process, but got Object assign thing in the page.
Is there any option I can try to feet IE11 compatibility?
Here is my current .babelrc and nuxt.config.js.
.babelrc
{
"presets": [
[
"env",
{
"modules": false
}
],
[ "vue-app",
{
"useBuiltIns": true,
"targets": {
"ie": 9,
"uglify": true
}
}
]
],
"plugins": [
"#babel/plugin-transform-object-assign",
"transform-vue-jsx",
[
"module-resolver",
{
"root": [
"./src"
],
"alias": {
"~sbdc": "./src/sbdc"
}
}
]
]
}
build option in nuxt.config.js
build: {
babel: {
presets: [
['vue-app', {
useBuiltIns: true,
targets: { ie: 9, uglify: true }
}
]
]
},
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/](babel-polyfill|moment|lodash|axios|get-size|jquery|js-cookie|jwt-decode|numeral|vuetify)[\\/]/,
name: 'utilityVendor'
}
}
}
},
output: {
publicPath: serviceConfig.pwa_publicPath || false
},
extractCSS: true,
plugins: [
new webpack.ProvidePlugin( {
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
} )
]
}
Thanks for sharing you solutions!
======= Edited in 0114 =============
Etra information #1.
When I look at the error on ie11 browser, it automatically transform code like below
return {layout:"popup",data:[{resultBody:Object.assign(Object.create(null), ... sorry, sensitive data
while the original code is...
asyncData: async function ({req}) {
return {
resultBody: req.body,
};
},
req.body is supported by body-parser.

After hours of struggling, I solved this with not good way(In my thought).
I just add object-assign polyfill js to nuxt.js
module.exports = {
...
head: {
script: [ { src: '/js/object-assign.js' } ]
},
...
};
But I still want to know the proper way to apply babel-polyfill into nuxt project.

Related

Why are absolute imports not working in my react-native expo project?

An example of the imports follows:
import { useAppDispatch, useAppSelector } from '~/redux/hooks'
import * as walletActions from '~/redux/wallet/actions'
import { actions, selectState as selectWalletState } from '~/redux/wallet/slice'
import { multichain } from '~/services/multichain'
import { config } from '~/settings/config'
In my tsconfig.json...
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*":["./src/*"]
},
...
This all compiles, and typescript understands my imports; I can click around them in VSCode.
However, when I open the app in Expo, I get the error
Unable to resolve module ~/redux/hooks from ... ~/redux/hooks could not be found within the project or in these directories:
node_modules
Here is my babel.config.js
module.exports = function (api) {
api.cache(true)
return {
presets: ['babel-preset-expo'],
plugins: [
['react-native-reanimated/plugin'],
[
'module:react-native-dotenv',
{
envName: 'APP_ENV',
moduleName: '#env',
path: '.env',
},
],
[
'module-resolver',
{
alias: {
'~/': './src/',
},
},
],
],
}
}

vue plugin pwa sw.js not found

I have 1 app using the vue pwa plugin, it works great.
The vuejs config for the app looks like this:
const WebpackNotifierPlugin = require('webpack-notifier')
module.exports = {
lintOnSave: false,
css: {
loaderOptions: {
sass: {
implementation: require('sass')
}
}
},
transpileDependencies: [
'vuex-module-decorators',
'vuex-persist'
],
pwa: {
name: 'MyApp',
themeColor: '#000000',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'dev/sw.js',
// ...other Workbox options...
}
},
configureWebpack: {
devServer:{
historyApiFallback: true,
},
plugins: [
new WebpackNotifierPlugin(),
],
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: 3,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `npm.${packageName.replace('#', '')}`;
},
},
},
},
},
},
}
I have another app, exactly the same, vue2, beufy etc etc.. i installed the same stuff via the vue pwa plugin and the config looks exactly the same but when i run build it says it cannot find the sw.js file:
Error: ENOENT: no such file or directory, open 'dev/sw.js'
I have created a uber basic vue app which does the same thing here: https://github.com/johndcarmichael/vue-pwa-sw-not-found
Has anyone else got this issue, and how did you resolve it?
You are not having dev/sw.js in your project, as you set in swSrc. InjectManifest means take this sw.js source file and write precache manifest into it, producing the final service-worker.js file.

Vue SFC styles not being extracted in webpack production build

Trying to add vue (and SFCs) to my webpack app. The <template> and <script> blocks work fine, but for some reason the styles in the <style> block are not being extracted for production build.
In the dev build, it's extracting the .vue <style> block to a separate css file (named for the entrypoint). Which is OK but I'd prefer they went into my main stylesheet.
But no matter what I try, I can't get any .vue styles to show up (in any file) for the production build.
This is an abbreviated version of my webpack config:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
...
module.exports = (env) => {
return {
entry: {
app: ["./src/polyfills.js", "./src/scss/styles.scss", "./src/app.js"],
...
testview: "./src/js/views/TestView.js"
},
output: {
path: assets,
filename: "[name].[hash].js",
publicPath: "/static/"
},
resolve: {
modules: ["node_modules", "src"],
alias: {
vue$: "vue/dist/vue.esm.js"
},
extensions: ["*", ".js", ".vue"]
},
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader"
},
{
test: /\.js?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: [
[
"#babel/preset-env",
{
targets: {
browsers: ["> 1%", "last 2 versions", "ie >= 11"]
}
}
]
],
plugins: ["#babel/plugin-proposal-class-properties"],
code: true,
comments: true,
cacheDirectory: true,
babelrc: false
}
}
]
},
{
test: /\.s?[ac]ss$/,
use: [
"vue-style-loader",
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
sourceMap: ifNotProduction()
}
},
{
loader: "postcss-loader",
options: {
ident: "postcss",
sourceMap: ifNotProduction(),
plugins: () =>
ifProduction([
require("autoprefixer")({
preset: "default"
}),
require("cssnano"),
require("css-mqpacker")
])
}
},
{
loader: "sass-loader",
options: {
sourceMap: ifNotProduction()
}
}
]
}
]
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2,
minSize: 0
},
styles: {
name: "styles",
test: /\.css$/,
chunks: "all",
enforce: true
}
}
},
occurrenceOrder: true
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "style.[hash].css"
}),
new HtmlWebpackPlugin({
hash: true,
inject: false,
template: "./src/jinja-templates/base.html.j2",
filename: `${templates}/base.html.j2`,
})
]
};
};
The .vue file I'm using is this demo one. I'm trying to import it into the entrypoint called 'testview' which contains simply:
import Vue from "vue";
import MainContent from "../components/main-content";
let MainComponent = Vue.extend(MainContent);
new MainComponent().$mount("#mainContent");
Did figure it out. I had to remove sideEffects: false from my package.json. This issue explains it further.
Still would like to know how to extract the .vue styles to my main stylesheet As it is now, the .vue styles are extracting to a separate stylesheet (dev and production).

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

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.

Syntax error when testing React component Jasmine and Webpack

I keep getting an error when trying to run a simple test using React, Karma, Jasmine and Webpack. The error is ' Uncaught SyntaxError: Unexpected token < ', I think my jsx isn't being processed to js, but I don't know why that is happening as I understand webpack should handle that using the babel loader. If anyone can provide advice I would be grateful
Here are my files
karma.conf.js
var webpack = require("webpack"),
path = require("path");
// Karma configuration
module.exports = function(config) {
config.set({
basePath: "",
frameworks: ["jasmine"],
files: [
"../test/!**!/!*.test.js"
],
preprocessors: {
"./test/!**!/!*.test.js": ["webpack"]
},
webpack: {
module: {
loaders: [
{
test: /\.jsx?$/i,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{ test: /\.less$/, loader: "style!css!less" }
]
},
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
])
],
resolve: {
root: __dirname,
extensions: [
'',
'.json',
'.js',
'.jsx'
]
}
},
webpackMiddleware: {
noInfo: true
},
plugins: [
require("karma-webpack"),
require("karma-jasmine"),
require("karma-chrome-launcher")
],
reporters: ["dots"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false
});
};
my test file example.test.js
var Comp = require('../../../js/common/components/MyComp.jsx'),
React = require('react'),
TestUtils = React.addons.TestUtils;
describe("Component Test", function() {
it("renders an h1", function () {
var component = TestUtils.renderIntoDocument(
<Comp/> // syntax error here
);
var h2 = TestUtils.findRenderedDOMComponentWithTag(
component, 'h2'
);
expect(h1).toExist();
});
});
So the syntax error happens at < Comp... . Thanks!
Apologise it was an error in setting the correct path to the test file.
files: [
"../test/**/*.test.js"
],
preprocessors: {
"../test/**/*.test.js": ["webpack"]
},