Socket
Socket
Sign inDemoInstall

@ywjt/spa-builder

Package Overview
Dependencies
885
Maintainers
2
Versions
10
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @ywjt/spa-builder

> TODO: description


Version published
Maintainers
2
Created

Readme

Source

@ywjt/spa-builder

TODO: description

Usage

const spaBuilder = require('@ywjt/spa-builder');

适用于单页面应用

创建项目目录

cp -r common_frontend/packages/antd_pure demo

添加公共库

cd demo
git init
git add .
git ci -m 'init'
git remote add common https://ywgit.gz4399.com/ywkf/common_frontend.git
git subtree add --prefix=common common master --squash
cd src
ln -s ../common/packages/app_common_spa_react16class_antd3_dva2 common

app及打包环境准备

cd demo
yarn install
cd common/build_webpack5_spa
yarn install

启动

cd demo
yarn start

登录认证

默认登录认证,若要切换到无登录认证,在src/route.jsx中改掉BasicLayout,并且注释掉srx/index.js中认证相关代码即可

src/route.jsx

// import AuthLayout from './common/layout/AuthLayout'
// import BasicLayout from './common/layout/BasicLayout'
import BasicLayout from './common/layoutWithoutLogin/BasicLayout'
...

const customRoutes = [
  // <Route path="/auth" component={AuthLayout} />,
	<Route path="/" component={withRouteConfig(BasicLayout)} />
]

src/index.jsx

...
const dvaConfig = {
  history: browserHistory,
  onError(error, dispatch) {
    if (error.response && error.response.config) {
      error.preventDefault();
      const method = error.response.config.method;
      if (method === 'get' && error.response.data.code === 999) {
        dispatch({
          type: 'global/showMsg',
          payload: { message: '登录信息已过期, 请重新登录。' },
        });
        // Cookie.remove(jwt.key);
        // Cookie.remove('_xsrf');
        // window.history.pushState(null, '登录页', '/auth')
        return;
      }
      dispatch({
        type: 'global/showMsg',
        payload: { message: error.message, type: 'error' },
      });
    } else {
      console.error(error);
    }
  },
};
...

覆盖默认的接口地址

默认的登录接口地址为/api/login,假设项目中登录接口地址为/api/auth/local,需要覆盖src/common/models/authApi.jsx中的接口地址,操作如下:

复制一份 auth model,改掉登录接口

cd src/models
cp ../common/models/{auth.jsx, authApi.jsx} .
vi authApi.jsx // 将/login 修改为/auth/local即可

在 models 注册入口剔除 common 中的 auth model

修改src/index.jsx

// 修改前
const commonModels = commonContext.keys().map(key => commonContext(key).default);

// 修改后
const commonModels = commonContext.keys().map(key => commonContext(key).default).filter(o => o.namespace !== 'auth');

在项目中修改webpack配置

在项目根据路下添加webpack.config.js,内容示例:

const path =require('path');
const CopyWebpackPlugin = require('../common/build_webpack5_spa/node_modules/copy-webpack-plugin')
const HtmlWebpackTagsPlugin = require('../common/build_webpack5_spa/node_modules/html-webpack-tags-plugin')
const { AlterAssetTagsPlugin } = require('./webpack.plugins.js');
module.exports = function (config) {
  if(!config.plugins) {
    config.plugins = [];
  }
  config.plugins.push(
    new CopyWebpackPlugin({patterns: [
      {from: path.resolve(__dirname, 'public/feishu'), to: 'feishu', toType: "dir"},
      {from: path.resolve(__dirname, 'src/hello.js'), to: 'hello.js', toType: "file"}
    ]}),
    new HtmlWebpackTagsPlugin({ tags: ['hello.js'], append: true })
  );
  config.plugins.push(new AlterAssetTagsPlugin())
  return config;
}

修改已有webpack.plugins的配置

方法一(野路子):基于某个特征找到plugin进行修改

const path =require('path');
module.exports = function (config) {
  if(!config.plugins) {
    config.plugins = [];
  }
  try {
    config.plugins.forEach(item => {
      if(item.userOptions && item.userOptions.filename === 'index.html') {
        item.userOptions.meta = {
          name: 'viewport',
          content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no'
        }
        throw new Error('break');
      }
    })
  } catch(err) {
  }
  return config;
}

方法二:某些插件提供支持,如html-webpack-plugin提供hooks 比如插入meta标签,方法如下:

在项目根目录下创建webpack.plugins.js,自己写一个webpack插件:

const HtmlWebpackPlugin = require('../common/build_webpack5_spa/node_modules/html-webpack-plugin');

class AlterAssetTagsPlugin {
  apply (compiler) {
    compiler.hooks.compilation.tap('AlterAssetTagsPlugin', (compilation) => {
      HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(
        'AlterAssetTagsPlugin',
        (data, cb) => {
          data.assetTags.meta = [{
            tagName: 'meta',
            attributes: {
              name: 'viewport',
              content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no'
            }
          }];
          cb(null, data)
        }
      )
    })
  }
}

exports.AlterAssetTagsPlugin = AlterAssetTagsPlugin;

在项目根目录下创建webpack.config.js,内容如下:

const { AlterAssetTagsPlugin } = require('./webpack.plugins.js');

module.exports = function (config) {
  if(!config.plugins) {
    config.plugins = [];
  }
  config.plugins.push(new AlterAssetTagsPlugin())
  return config;
}

FAQs

Last updated on 27 Sep 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc