Vue.js+BootstrapVueで作成したサイトをNuxt.jsで書き直したら Unexpected token import
のエラーが出て動かなくなりました。
エラー
package.json
{
"name": "nuxt-bootstrap",
"scripts": {
"dev": "nuxt"
},
"dependencies": {
"bootstrap-vue": "^2.0.0-rc.11",
"nuxt": "^1.4.2"
}
}
plugins/bootstrap.js
import Vue from 'vue';
import bAlert from 'bootstrap-vue/es/components/alert/alert';
Vue.component('b-alert', bAlert);
pages/index.vue
<template>
<div>
<b-alert show>Ciao!</b-alert>
</div>
</template>
nuxt.config.js
module.exports = {
css: [
'bootstrap/dist/css/bootstrap.css',
'bootstrap-vue/dist/bootstrap-vue.css',
],
plugins: [
'@/plugins/bootstrap',
],
};
解決法
webpack-node-externalsを使え とのこと。
yarn add -D webpack-node-externals
nuxt.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
build: {
extend(config, { isServer }) {
if (isServer) {
config.externals = [
nodeExternals({
whitelist: [/\.(?!(?:js|json)$).{1,5}$/i, /^bootstrap-vue/],
}),
];
}
},
},
css: [
'bootstrap/dist/css/bootstrap.css',
'bootstrap-vue/dist/bootstrap-vue.css',
],
plugins: [
'@/plugins/bootstrap',
],
};
直りました。
なんでこうしなきゃならないのか分かっていないので、教えていただけると大変ありがたいです。
余談
build.babel.babelrc
は v1.4.2では常にfalseになる ため extend()
で書き換える必要があります 1。
nuxt.config.js/build
extend(config, { isClient, isServer }) {
config.module.rules
.filter(rule => rule.loader === 'babel-loader')
.map(rule => {
rule.options.babelrc = true;
});
},
// babel: {
// babelrc: true, // falseで上書きされてしまう
// },
追記
Nuxt2で動かなくなりました。 build.transpile
オプションを使用しても同様です。