0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

nuxt.config.js忘備録

Last updated at Posted at 2021-07-01
nuxt.config.js
//↓nuxt.config.jsメモ↓
//nuxt.config.jsはプロジェクト全体に適用させる設定を行う
//process.envにclient側で使用するものは書かない。※動かないから
//nuxtjs/proxyはgenerateモードでは使えない
//process.cwd()はサーバーサイドでないと有効ではない。client側では "/" が表示される。
//process.serverとprocess.clientはnuxt.config.jsでは使えない。
//クライアント側ではlocation.pathnameを使う
//process.envには関数は入れられない。""で囲まれてテキスト化される。

/* staticAssets ディレクトリ用変数 start */
import { version } from './package.json';
/* staticAssets ディレクトリ用変数 end */

/* manifest.js用のルート格納変数 start */
let myRoutesTxt = "";
/* manifest.js用のルート格納変数 end */

/* ★★★本番公開用プロジェクトの名前を設定する★★★ start */
/* 例:const productName = "project-nuxt"; */
const productName = "project-nuxt";
/* ★★★本番公開用プロジェクトの名前を設定する★★★ end */

/* ★★★本番公開用プロジェクトのルートを設定する(アップロード先)★★★ start */
/* 例:const productRoot = `/sample-path/${productName}` */
/* 末尾にスラッシュは入れない */
const productRoot = `/sample-path/${productName}`;
/* ★★★本番公開用プロジェクトのルートを設定する(アップロード先)★★★ end */

/* ★★★本番公開用プロジェクトの出力先を設定する★★★ start */
/* 例:`./${productName}` とか `../${productName}` とか `../../${productName}` 他… */
const productGenPath = `../_dist/${productName}`;
/* ★★★本番公開用プロジェクトの出力先を設定する★★★ end */

//外部モジュールのパスなど
const siteMeta = {};
siteMeta.impPath = process.env.impPath = process.env.NODE_ENV !== "production" ? "http://localhost:8888" : "";

//baseURLはproxyを使っているときは使えない。その時は接頭辞の「prefix」を使う。
const axiosHost = process.env.NODE_ENV !== "production" ? { prefix: "" } : { baseURL: "" };

export default {

    loading: process.env.NODE_ENV !== "production" ? true : false,
    target: 'static',
    mode: "univarsal",
    srcDir: "app",

    //環境変数の設定(公開用)
    publicRuntimeConfig: {
        staticRoot: productRoot,
    },
    //環境変数の設定(非公開用)
    privateRuntimeConfig: {
        secret: null
    },

    // Build Configuration(https://go.nuxtjs.dev/config-build)
    build: {
        // transpile: [/^element-ui/],//element-ui設定
        extend(config, { isDev, isClient, loaders }) {//webpack設定
            config.output.jsonpFunction = 'webpackLoad';//既存のwebpackグローバル変数との重複を避ける
            const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')
            config.plugins.push(new HardSourceWebpackPlugin());
            loaders.imgUrl.limit = 10000;
        },
        //_nuxt以下に入るファイル(build対象)
        filenames: {
            app: () => 'app/[id].js',
            chunk: () => 'chunk/[id].js',
            css: () => 'css/[id].js',
        },
        parallel: true,
        cache: true,
        hardsource: true,
    },

    // ルーティングの設定
    router: {
        // trailingSlash: true,
        //プロジェクトのルートパス
        base: process.env.NODE_ENV !== 'production' ? '/' : productRoot,
        middleware: ["util-route"],
        extendRoutes(routes, resolve) {
            // 自作manifest.jsの作成
            routes.forEach((route, idx) => {
                if (idx == 0) {
                    myRoutesTxt += `"${route.path}"`;
                }
                else {
                    myRoutesTxt += `,"${route.path}"`;
                }
            });
        }
    },

    // generateの設定
    generate: {
        //distの出力先
        dir: productGenPath,
        crawler: false,
        // fallback: '404.html',
        //動的なパスの際に対応
        routes() {
            // 配列で返す必要がある

            const states = require('./_env-my-app/route-state.js').default;
            return [].concat(
                states.map(state => {
                    const setRoute = `/sample-path/${state}`;
                    if (myRoutesTxt == "") {
                        myRoutesTxt += `"${setRoute}"`;
                    }
                    else { myRoutesTxt += `,"${setRoute}"`; }
                    return `${setRoute}/`;
                }),
                states.map(state => {
                    const setRoute = `/sample-path/${state}`;
                    if (myRoutesTxt == "") {
                        myRoutesTxt += `"${setRoute}"`;
                    }
                    else { myRoutesTxt += `,"${setRoute}"`; }
                    return `${setRoute}/`;
                })
            );

        },
        done() {
            if (process.env.MY_CLUSTER) {
                const content_manifest = `__NUXT_JSONP__("manifest.js",{routes:[${myRoutesTxt}]})`;
                const fs = require('fs');
                fs.writeFile(`${productGenPath}/_nuxt/static/${version}/manifest.js`, content_manifest, function (err) {
                    if (err) {
                        console.log("自作のmanifest.jsの作成に失敗しました")
                        throw err;
                    }
                    console.log('自作のmanifest.jsが作成されました');
                });
            }
            else {
                console.log("clusterによるgenerateではありません");
            }
        },
        staticAssets: {
            version
        },
    },

    // Axios module configuration(https://go.nuxtjs.dev/config-axios)
    axios: axiosHost,

    proxy: {
        '/api': {
            target: 'http://localhost:3030',
            // pathRewrite: {
            // '^/api': ''
            // }
        },
        '/sample-path': {
            target: 'http://localhost:8888',
            // pathRewrite: {
            //'^http://localhost:8888': ''
            // }
        }
    },

    // Global page headers (https://go.nuxtjs.dev/config-head)
    head: {
        base: {
            // href: process.env.NODE_ENV
            //     !== 'production' ? 'localhost:8888/' : `/`,
            // src: process.env.NODE_ENV !==
            //     'production' ? 'localhost:8888/' : `/`,
        },
        meta: [
            { charset: "utf-8" },
            { name: 'viewport', content: 'width=device-width, initial-scale=1' },
            { name: "Targeted Geographic Area", content: "Japan" },
            { name: "coverage", content: "Japan" },
            { name: "rating", content: "general" },
            { name: "content-language", content: "ja" },
            { name: "format-detection", content: "telephone=no" },
        ],
        link: [],
        script: [
            // pbody…body直後, body…bodyタグ内の後部
            //body:true or false, pbody: true or false, mode:"client"
            //{src:'https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'},
        ]
    },

    //グローバルに適用させるCSSの設定
    css: [
        '~/assets/scss/style.scss',
    ],

    // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
    plugins: [
        '@/plugins/axios-log',
        '@/plugins/axios-conf',
        '@/plugins/gen-static-root',
        '@/plugins/siteMeta',
        '@/plugins/window-resize',
    ],

    // Auto import components (https://go.nuxtjs.dev/config-components)
    components: true,

    // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
    buildModules: [
    ],

    // Modules (https://go.nuxtjs.dev/config-modules)
    modules: [
        // https://go.nuxtjs.dev/axios
        '@nuxtjs/axios',
        '@nuxtjs/proxy',
        '@nuxtjs/style-resources',
        '@nuxtjs/redirect-module',
        ['vue-scrollto/nuxt', { duration: 300 }]
    ],

    redirect: [
        {
            from: '^(\\/[^\\?]*[^\\/])(\\?.*)?$',
            to: '$1/$2',
            statusCode: 301
        }
    ],

    //コンポーネントからでも使えるscssを設定
    styleResources: {
        scss: []
    },

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?